Compare commits
83 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| bb14a955a0 | |||
| dac1506680 | |||
| 3946a08f40 | |||
| ee0519aacc | |||
| dec1e3fdda | |||
| f54e900716 | |||
| 7e8b5749fa | |||
| febf902dc4 | |||
| 04b51f2610 | |||
| b2a4f57d64 | |||
| 0ce7d92a8b | |||
| 7a67fe7dde | |||
| 00b4670b8b | |||
| 7633a951e6 | |||
| 4ff64c6209 | |||
| 22023fa9e7 | |||
| 85e0b53c33 | |||
| 6eaa231587 | |||
| befb7509de | |||
| 09bf0b86d8 | |||
| b5d45fa9f5 | |||
| a6a633d5c1 | |||
| e83e8001da | |||
| 0386898476 | |||
| 5e777fd2a2 | |||
| 3c71fda648 | |||
| 42329a038a | |||
| 10f3983f0b | |||
| e9de7f95a7 | |||
| a4113acd15 | |||
| 9c8e56fc96 | |||
| c78cb57c41 | |||
| eb15b2ba75 | |||
| 279edb6f24 | |||
| c51a34bf4b | |||
| e8d144d2a2 | |||
| a760e8364f | |||
| fa7cae59c0 | |||
| 8780fa6ccf | |||
| ab2df0ae33 | |||
| 23757f3ac0 | |||
| df7296cfe1 | |||
| 776276d5a4 | |||
| eea45a22fa | |||
| ddacb04f99 | |||
| 09561254a8 | |||
| 73a8356b10 | |||
| 8db75266d0 | |||
| 6c30565d40 | |||
| b223a29603 | |||
| 8ed72ae087 | |||
| 62b8c7aee0 | |||
| 6145dfcca0 | |||
| 4580c88c0b | |||
| 061ba65d20 | |||
| 457386ad08 | |||
| fce04dc48b | |||
| 81534ab387 | |||
| 409a6f93b2 | |||
| 55c294c013 | |||
| 70db372466 | |||
| 8cc427daba | |||
| 8fde772957 | |||
| d8dc23bde9 | |||
| 1c83ef75a2 | |||
| 95e410db88 | |||
| 13d3fba86b | |||
| 3ab4f42ebb | |||
| b8d2aebf09 | |||
| 20e818ad05 | |||
| 542186aa49 | |||
| c478d1bdbb | |||
| 7fd2222976 | |||
| e86adb2ec8 | |||
| 34ac0e895d | |||
| bd4319f2bc | |||
| 696ab1a752 | |||
| d3ff66e911 | |||
| 1954b59167 | |||
| e2fac991dc | |||
| 8ba35eadd4 | |||
| 7446f5ad7b | |||
| 81a3e02474 |
@@ -1,4 +1,6 @@
|
||||
---
|
||||
model: openai/gpt-5
|
||||
reasoningEffort: medium
|
||||
description: ALWAYS use this when writing docs
|
||||
---
|
||||
|
||||
|
||||
@@ -42,3 +42,6 @@
|
||||
| 2025-08-06 | 147,067 (+5,471) | 158,309 (+2,557) | 305,376 (+8,028) |
|
||||
| 2025-08-07 | 152,591 (+5,524) | 160,889 (+2,580) | 313,480 (+8,104) |
|
||||
| 2025-08-08 | 158,187 (+5,596) | 163,448 (+2,559) | 321,635 (+8,155) |
|
||||
| 2025-08-09 | 162,770 (+4,583) | 165,721 (+2,273) | 328,491 (+6,856) |
|
||||
| 2025-08-10 | 165,695 (+2,925) | 167,109 (+1,388) | 332,804 (+4,313) |
|
||||
| 2025-08-11 | 169,297 (+3,602) | 167,953 (+844) | 337,250 (+4,446) |
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
},
|
||||
"cloud/core": {
|
||||
"name": "@opencode/cloud-core",
|
||||
"version": "0.0.0",
|
||||
"version": "0.4.19",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-sts": "3.782.0",
|
||||
"drizzle-orm": "0.41.0",
|
||||
@@ -27,7 +27,7 @@
|
||||
},
|
||||
"cloud/function": {
|
||||
"name": "@opencode/cloud-function",
|
||||
"version": "0.3.130",
|
||||
"version": "0.4.19",
|
||||
"dependencies": {
|
||||
"@ai-sdk/anthropic": "2.0.0",
|
||||
"@ai-sdk/openai": "2.0.2",
|
||||
@@ -47,7 +47,7 @@
|
||||
},
|
||||
"cloud/web": {
|
||||
"name": "@opencode/cloud-web",
|
||||
"version": "0.0.0",
|
||||
"version": "0.4.19",
|
||||
"dependencies": {
|
||||
"@kobalte/core": "0.13.9",
|
||||
"@openauthjs/solid": "0.0.0-20250322224806",
|
||||
@@ -66,7 +66,7 @@
|
||||
},
|
||||
"packages/function": {
|
||||
"name": "@opencode/function",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.19",
|
||||
"dependencies": {
|
||||
"@octokit/auth-app": "8.0.1",
|
||||
"@octokit/rest": "22.0.0",
|
||||
@@ -81,7 +81,7 @@
|
||||
},
|
||||
"packages/opencode": {
|
||||
"name": "opencode",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.19",
|
||||
"bin": {
|
||||
"opencode": "./bin/opencode",
|
||||
},
|
||||
@@ -120,7 +120,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ai-sdk/amazon-bedrock": "2.2.10",
|
||||
"@ai-sdk/anthropic": "1.2.12",
|
||||
"@octokit/webhooks-types": "7.6.1",
|
||||
"@standard-schema/spec": "1.0.0",
|
||||
"@tsconfig/bun": "1.0.7",
|
||||
@@ -134,7 +133,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@opencode-ai/plugin",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.19",
|
||||
"dependencies": {
|
||||
"@opencode-ai/sdk": "workspace:*",
|
||||
},
|
||||
@@ -146,7 +145,7 @@
|
||||
},
|
||||
"packages/sdk/js": {
|
||||
"name": "@opencode-ai/sdk",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.19",
|
||||
"devDependencies": {
|
||||
"@hey-api/openapi-ts": "0.80.1",
|
||||
"@tsconfig/node22": "catalog:",
|
||||
@@ -155,9 +154,9 @@
|
||||
},
|
||||
"packages/web": {
|
||||
"name": "@opencode/web",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.19",
|
||||
"dependencies": {
|
||||
"@astrojs/cloudflare": "^12.5.4",
|
||||
"@astrojs/cloudflare": "12.6.3",
|
||||
"@astrojs/markdown-remark": "6.3.1",
|
||||
"@astrojs/solid-js": "5.1.0",
|
||||
"@astrojs/starlight": "0.34.3",
|
||||
@@ -230,11 +229,11 @@
|
||||
|
||||
"@apidevtools/json-schema-ref-parser": ["@apidevtools/json-schema-ref-parser@11.9.3", "", { "dependencies": { "@jsdevtools/ono": "^7.1.3", "@types/json-schema": "^7.0.15", "js-yaml": "^4.1.0" } }, "sha512-60vepv88RwcJtSHrD6MjIL6Ta3SOYbgfnkHb+ppAVK+o9mXprRtulx7VlRl3lN3bbvysAfCS7WMVfhUYemB0IQ=="],
|
||||
|
||||
"@astrojs/cloudflare": ["@astrojs/cloudflare@12.6.0", "", { "dependencies": { "@astrojs/internal-helpers": "0.6.1", "@astrojs/underscore-redirects": "1.0.0", "@cloudflare/workers-types": "^4.20250507.0", "tinyglobby": "^0.2.13", "vite": "^6.3.5", "wrangler": "^4.14.1" }, "peerDependencies": { "astro": "^5.0.0" } }, "sha512-pQ8bokC59GEiXvyXpC4swBNoL7C/EknP+82KFzQwgR/Aeo5N1oPiAoPHgJbpPya/YF4E26WODdCQfBQDvLRfuw=="],
|
||||
"@astrojs/cloudflare": ["@astrojs/cloudflare@12.6.3", "", { "dependencies": { "@astrojs/internal-helpers": "0.7.1", "@astrojs/underscore-redirects": "1.0.0", "@cloudflare/workers-types": "^4.20250507.0", "tinyglobby": "^0.2.13", "vite": "^6.3.5", "wrangler": "^4.14.1" }, "peerDependencies": { "astro": "^5.0.0" } }, "sha512-xhJptF5tU2k5eo70nIMyL1Udma0CqmUEnGSlGyFflLqSY82CRQI6nWZ/xZt0ZvmXuErUjIx0YYQNfZsz5CNjLQ=="],
|
||||
|
||||
"@astrojs/compiler": ["@astrojs/compiler@2.12.2", "", {}, "sha512-w2zfvhjNCkNMmMMOn5b0J8+OmUaBL1o40ipMvqcG6NRpdC+lKxmTi48DT8Xw0SzJ3AfmeFLB45zXZXtmbsjcgw=="],
|
||||
|
||||
"@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="],
|
||||
"@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.7.1", "", {}, "sha512-7dwEVigz9vUWDw3nRwLQ/yH/xYovlUA0ZD86xoeKEBmkz9O6iELG1yri67PgAPW6VLL/xInA4t7H0CK6VmtkKQ=="],
|
||||
|
||||
"@astrojs/markdown-remark": ["@astrojs/markdown-remark@6.3.1", "", { "dependencies": { "@astrojs/internal-helpers": "0.6.1", "@astrojs/prism": "3.2.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "hast-util-to-text": "^4.0.2", "import-meta-resolve": "^4.1.0", "js-yaml": "^4.1.0", "mdast-util-definitions": "^6.0.0", "rehype-raw": "^7.0.0", "rehype-stringify": "^10.0.1", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.1", "remark-smartypants": "^3.0.2", "shiki": "^3.0.0", "smol-toml": "^1.3.1", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "unist-util-visit": "^5.0.0", "unist-util-visit-parents": "^6.0.1", "vfile": "^6.0.3" } }, "sha512-c5F5gGrkczUaTVgmMW9g1YMJGzOtRvjjhw6IfGuxarM6ct09MpwysP10US729dy07gg8y+ofVifezvP3BNsWZg=="],
|
||||
|
||||
@@ -908,7 +907,7 @@
|
||||
|
||||
"@types/babel__traverse": ["@types/babel__traverse@7.20.7", "", { "dependencies": { "@babel/types": "^7.20.7" } }, "sha512-dkO5fhS7+/oos4ciWxyEyjWe48zmG6wbCheo/G2ZnHx4fs3EU6YC6UM8rk56gAjNJ9P3MTH2jo5jb92/K6wbng=="],
|
||||
|
||||
"@types/bun": ["@types/bun@1.2.19", "", { "dependencies": { "bun-types": "1.2.19" } }, "sha512-d9ZCmrH3CJ2uYKXQIUuZ/pUnTqIvLDS0SK7pFmbx8ma+ziH/FRMoAq5bYpRG7y+w1gl+HgyNZbtqgMq4W4e2Lg=="],
|
||||
"@types/bun": ["@types/bun@1.2.20", "", { "dependencies": { "bun-types": "1.2.20" } }, "sha512-dX3RGzQ8+KgmMw7CsW4xT5ITBSCrSbfHc36SNT31EOUg/LA9JWq0VDdEXDRSe1InVWpd2yLUM1FUF/kEOyTzYA=="],
|
||||
|
||||
"@types/cacheable-request": ["@types/cacheable-request@6.0.3", "", { "dependencies": { "@types/http-cache-semantics": "*", "@types/keyv": "^3.1.4", "@types/node": "*", "@types/responselike": "^1.0.0" } }, "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw=="],
|
||||
|
||||
@@ -2570,6 +2569,8 @@
|
||||
|
||||
"@astrojs/cloudflare/vite": ["vite@6.3.5", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ=="],
|
||||
|
||||
"@astrojs/markdown-remark/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="],
|
||||
|
||||
"@astrojs/mdx/@astrojs/markdown-remark": ["@astrojs/markdown-remark@6.3.3", "", { "dependencies": { "@astrojs/internal-helpers": "0.6.1", "@astrojs/prism": "3.3.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "hast-util-to-text": "^4.0.2", "import-meta-resolve": "^4.1.0", "js-yaml": "^4.1.0", "mdast-util-definitions": "^6.0.0", "rehype-raw": "^7.0.0", "rehype-stringify": "^10.0.1", "remark-gfm": "^4.0.1", "remark-parse": "^11.0.0", "remark-rehype": "^11.1.2", "remark-smartypants": "^3.0.2", "shiki": "^3.2.1", "smol-toml": "^1.3.4", "unified": "^11.0.5", "unist-util-remove-position": "^5.0.0", "unist-util-visit": "^5.0.0", "unist-util-visit-parents": "^6.0.1", "vfile": "^6.0.3" } }, "sha512-DDRtD1sPvAuA7ms2btc9A7/7DApKqgLMNrE6kh5tmkfy8utD0Z738gqd3p5aViYYdUtHIyEJ1X4mCMxfCfu15w=="],
|
||||
|
||||
"@astrojs/mdx/source-map": ["source-map@0.7.6", "", {}, "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ=="],
|
||||
@@ -2750,12 +2751,16 @@
|
||||
|
||||
"@tufjs/models/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="],
|
||||
|
||||
"@types/bun/bun-types": ["bun-types@1.2.20", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-pxTnQYOrKvdOwyiyd/7sMt9yFOenN004Y6O4lCcCUoKVej48FS5cvTw9geRaEcB9TsDZaJKAxPTVvi8tFsVuXA=="],
|
||||
|
||||
"ai/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@3.0.1", "", { "dependencies": { "@ai-sdk/provider": "2.0.0", "@standard-schema/spec": "^1.0.0", "eventsource-parser": "^3.0.3", "zod-to-json-schema": "^3.24.1" }, "peerDependencies": { "zod": "^3.25.76 || ^4" } }, "sha512-/iP1sKc6UdJgGH98OCly7sWJKv+J9G47PnTjIj40IJMUQKwDrUMyf7zOOfRtPwSuNifYhSoJQ4s1WltI65gJ/g=="],
|
||||
|
||||
"ansi-align/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
|
||||
|
||||
"anymatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"astro/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="],
|
||||
|
||||
"astro/diff": ["diff@5.2.0", "", {}, "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A=="],
|
||||
|
||||
"astro/esbuild": ["esbuild@0.25.8", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.8", "@esbuild/android-arm": "0.25.8", "@esbuild/android-arm64": "0.25.8", "@esbuild/android-x64": "0.25.8", "@esbuild/darwin-arm64": "0.25.8", "@esbuild/darwin-x64": "0.25.8", "@esbuild/freebsd-arm64": "0.25.8", "@esbuild/freebsd-x64": "0.25.8", "@esbuild/linux-arm": "0.25.8", "@esbuild/linux-arm64": "0.25.8", "@esbuild/linux-ia32": "0.25.8", "@esbuild/linux-loong64": "0.25.8", "@esbuild/linux-mips64el": "0.25.8", "@esbuild/linux-ppc64": "0.25.8", "@esbuild/linux-riscv64": "0.25.8", "@esbuild/linux-s390x": "0.25.8", "@esbuild/linux-x64": "0.25.8", "@esbuild/netbsd-arm64": "0.25.8", "@esbuild/netbsd-x64": "0.25.8", "@esbuild/openbsd-arm64": "0.25.8", "@esbuild/openbsd-x64": "0.25.8", "@esbuild/openharmony-arm64": "0.25.8", "@esbuild/sunos-x64": "0.25.8", "@esbuild/win32-arm64": "0.25.8", "@esbuild/win32-ia32": "0.25.8", "@esbuild/win32-x64": "0.25.8" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-vVC0USHGtMi8+R4Kz8rt6JhEWLxsv9Rnu/lGYbPR8u47B+DCBksq9JarW0zOO7bs37hyOK1l2/oqtbciutL5+Q=="],
|
||||
@@ -2828,8 +2833,6 @@
|
||||
|
||||
"nypm/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
|
||||
|
||||
"opencode/@ai-sdk/anthropic": ["@ai-sdk/anthropic@1.2.12", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "@ai-sdk/provider-utils": "2.2.8" }, "peerDependencies": { "zod": "^3.0.0" } }, "sha512-YSzjlko7JvuiyQFmI9RN1tNZdEiZxc+6xld/0tq/VkJaHpEzGAb1yiNxxvmYVcjvfu/PcvCxAAYXmTYQQ63IHQ=="],
|
||||
|
||||
"opencode/@openauthjs/openauth": ["@openauthjs/openauth@0.4.3", "", { "dependencies": { "@standard-schema/spec": "1.0.0-beta.3", "aws4fetch": "1.0.20", "jose": "5.9.6" }, "peerDependencies": { "arctic": "^2.2.2", "hono": "^4.0.0" } }, "sha512-RlnjqvHzqcbFVymEwhlUEuac4utA5h4nhSK/i2szZuQmxTIqbGUxZ+nM+avM+VV4Ing+/ZaNLKILoXS3yrkOOw=="],
|
||||
|
||||
"opencontrol/@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.6.1", "", { "dependencies": { "content-type": "^1.0.5", "cors": "^2.8.5", "eventsource": "^3.0.2", "express": "^5.0.1", "express-rate-limit": "^7.5.0", "pkce-challenge": "^4.1.0", "raw-body": "^3.0.0", "zod": "^3.23.8", "zod-to-json-schema": "^3.24.1" } }, "sha512-oxzMzYCkZHMntzuyerehK3fV6A2Kwh5BD6CGEJSVDU2QNEhfLOptf2X7esQgaHZXHZY0oHmMsOtIDLP71UJXgA=="],
|
||||
@@ -2934,6 +2937,8 @@
|
||||
|
||||
"@astrojs/cloudflare/vite/esbuild": ["esbuild@0.25.8", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.8", "@esbuild/android-arm": "0.25.8", "@esbuild/android-arm64": "0.25.8", "@esbuild/android-x64": "0.25.8", "@esbuild/darwin-arm64": "0.25.8", "@esbuild/darwin-x64": "0.25.8", "@esbuild/freebsd-arm64": "0.25.8", "@esbuild/freebsd-x64": "0.25.8", "@esbuild/linux-arm": "0.25.8", "@esbuild/linux-arm64": "0.25.8", "@esbuild/linux-ia32": "0.25.8", "@esbuild/linux-loong64": "0.25.8", "@esbuild/linux-mips64el": "0.25.8", "@esbuild/linux-ppc64": "0.25.8", "@esbuild/linux-riscv64": "0.25.8", "@esbuild/linux-s390x": "0.25.8", "@esbuild/linux-x64": "0.25.8", "@esbuild/netbsd-arm64": "0.25.8", "@esbuild/netbsd-x64": "0.25.8", "@esbuild/openbsd-arm64": "0.25.8", "@esbuild/openbsd-x64": "0.25.8", "@esbuild/openharmony-arm64": "0.25.8", "@esbuild/sunos-x64": "0.25.8", "@esbuild/win32-arm64": "0.25.8", "@esbuild/win32-ia32": "0.25.8", "@esbuild/win32-x64": "0.25.8" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-vVC0USHGtMi8+R4Kz8rt6JhEWLxsv9Rnu/lGYbPR8u47B+DCBksq9JarW0zOO7bs37hyOK1l2/oqtbciutL5+Q=="],
|
||||
|
||||
"@astrojs/mdx/@astrojs/markdown-remark/@astrojs/internal-helpers": ["@astrojs/internal-helpers@0.6.1", "", {}, "sha512-l5Pqf6uZu31aG+3Lv8nl/3s4DbUzdlxTWDof4pEpto6GUJNhhCbelVi9dEyurOVyqaelwmS9oSyOWOENSfgo9A=="],
|
||||
|
||||
"@astrojs/mdx/@astrojs/markdown-remark/@astrojs/prism": ["@astrojs/prism@3.3.0", "", { "dependencies": { "prismjs": "^1.30.0" } }, "sha512-q8VwfU/fDZNoDOf+r7jUnMC2//H2l0TuQ6FkGJL8vD8nw/q5KiL3DS1KKBI3QhI9UQhpJ5dc7AtqfbXWuOgLCQ=="],
|
||||
|
||||
"@astrojs/solid-js/vite/esbuild": ["esbuild@0.25.8", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.8", "@esbuild/android-arm": "0.25.8", "@esbuild/android-arm64": "0.25.8", "@esbuild/android-x64": "0.25.8", "@esbuild/darwin-arm64": "0.25.8", "@esbuild/darwin-x64": "0.25.8", "@esbuild/freebsd-arm64": "0.25.8", "@esbuild/freebsd-x64": "0.25.8", "@esbuild/linux-arm": "0.25.8", "@esbuild/linux-arm64": "0.25.8", "@esbuild/linux-ia32": "0.25.8", "@esbuild/linux-loong64": "0.25.8", "@esbuild/linux-mips64el": "0.25.8", "@esbuild/linux-ppc64": "0.25.8", "@esbuild/linux-riscv64": "0.25.8", "@esbuild/linux-s390x": "0.25.8", "@esbuild/linux-x64": "0.25.8", "@esbuild/netbsd-arm64": "0.25.8", "@esbuild/netbsd-x64": "0.25.8", "@esbuild/openbsd-arm64": "0.25.8", "@esbuild/openbsd-x64": "0.25.8", "@esbuild/openharmony-arm64": "0.25.8", "@esbuild/sunos-x64": "0.25.8", "@esbuild/win32-arm64": "0.25.8", "@esbuild/win32-ia32": "0.25.8", "@esbuild/win32-x64": "0.25.8" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-vVC0USHGtMi8+R4Kz8rt6JhEWLxsv9Rnu/lGYbPR8u47B+DCBksq9JarW0zOO7bs37hyOK1l2/oqtbciutL5+Q=="],
|
||||
@@ -3060,10 +3065,6 @@
|
||||
|
||||
"local-pkg/pkg-types/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="],
|
||||
|
||||
"opencode/@ai-sdk/anthropic/@ai-sdk/provider": ["@ai-sdk/provider@1.1.3", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg=="],
|
||||
|
||||
"opencode/@ai-sdk/anthropic/@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@2.2.8", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "nanoid": "^3.3.8", "secure-json-parse": "^2.7.0" }, "peerDependencies": { "zod": "^3.23.8" } }, "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA=="],
|
||||
|
||||
"opencode/@openauthjs/openauth/@standard-schema/spec": ["@standard-schema/spec@1.0.0-beta.3", "", {}, "sha512-0ifF3BjA1E8SY9C+nUew8RefNOIq0cDlYALPty4rhUm8Rrl6tCM8hBT4bhGhx7I7iXD0uAgt50lgo8dD73ACMw=="],
|
||||
|
||||
"opencode/@openauthjs/openauth/aws4fetch": ["aws4fetch@1.0.20", "", {}, "sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g=="],
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode/cloud-core",
|
||||
"version": "0.0.0",
|
||||
"version": "0.4.22",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode/cloud-function",
|
||||
"version": "0.3.130",
|
||||
"version": "0.4.22",
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -2,7 +2,9 @@ import { Resource } from "sst"
|
||||
import { z } from "zod"
|
||||
import { issuer } from "@openauthjs/openauth"
|
||||
import { createSubjects } from "@openauthjs/openauth/subject"
|
||||
import { CodeProvider } from "@openauthjs/openauth/provider/code"
|
||||
import { GithubProvider } from "@openauthjs/openauth/provider/github"
|
||||
import { GoogleOidcProvider } from "@openauthjs/openauth/provider/google"
|
||||
import { CloudflareStorage } from "@openauthjs/openauth/storage/cloudflare"
|
||||
import { Account } from "@opencode/cloud-core/account.js"
|
||||
|
||||
@@ -30,6 +32,53 @@ export default {
|
||||
clientSecret: Resource.GITHUB_CLIENT_SECRET_CONSOLE.value,
|
||||
scopes: ["read:user", "user:email"],
|
||||
}),
|
||||
google: GoogleOidcProvider({
|
||||
clientID: Resource.GOOGLE_CLIENT_ID.value,
|
||||
scopes: ["openid", "email"],
|
||||
}),
|
||||
// email: CodeProvider({
|
||||
// async request(req, state, form, error) {
|
||||
// console.log(state)
|
||||
// const params = new URLSearchParams()
|
||||
// if (error) {
|
||||
// params.set("error", error.type)
|
||||
// }
|
||||
// if (state.type === "start") {
|
||||
// return Response.redirect(process.env.AUTH_FRONTEND_URL + "/auth/email?" + params.toString(), 302)
|
||||
// }
|
||||
//
|
||||
// if (state.type === "code") {
|
||||
// return Response.redirect(process.env.AUTH_FRONTEND_URL + "/auth/code?" + params.toString(), 302)
|
||||
// }
|
||||
//
|
||||
// return new Response("ok")
|
||||
// },
|
||||
// async sendCode(claims, code) {
|
||||
// const email = z.string().email().parse(claims.email)
|
||||
// const cmd = new SendEmailCommand({
|
||||
// Destination: {
|
||||
// ToAddresses: [email],
|
||||
// },
|
||||
// FromEmailAddress: `SST <auth@${Resource.Email.sender}>`,
|
||||
// Content: {
|
||||
// Simple: {
|
||||
// Body: {
|
||||
// Html: {
|
||||
// Data: `Your pin code is <strong>${code}</strong>`,
|
||||
// },
|
||||
// Text: {
|
||||
// Data: `Your pin code is ${code}`,
|
||||
// },
|
||||
// },
|
||||
// Subject: {
|
||||
// Data: "SST Console Pin Code: " + code,
|
||||
// },
|
||||
// },
|
||||
// },
|
||||
// })
|
||||
// await ses.send(cmd)
|
||||
// },
|
||||
// }),
|
||||
},
|
||||
storage: CloudflareStorage({
|
||||
namespace: env.AuthStorage,
|
||||
@@ -50,7 +99,14 @@ export default {
|
||||
})
|
||||
const user = (await userResponse.json()) as { email: string }
|
||||
email = user.email
|
||||
} else throw new Error("Unsupported provider")
|
||||
} else if (response.provider === "google") {
|
||||
if (!response.id.email_verified) throw new Error("Google email not verified")
|
||||
email = response.id.email as string
|
||||
}
|
||||
//if (response.provider === "email") {
|
||||
// email = response.claims.email
|
||||
//}
|
||||
else throw new Error("Unsupported provider")
|
||||
|
||||
if (!email) throw new Error("No email found")
|
||||
|
||||
|
||||
+447
-425
@@ -4,11 +4,11 @@ import { cors } from "hono/cors"
|
||||
import { HTTPException } from "hono/http-exception"
|
||||
import { zValidator } from "@hono/zod-validator"
|
||||
import { Resource } from "sst"
|
||||
import { generateText, streamText } from "ai"
|
||||
import { type ProviderMetadata, type LanguageModelUsage, generateText, streamText } from "ai"
|
||||
import { createAnthropic } from "@ai-sdk/anthropic"
|
||||
import { createOpenAI } from "@ai-sdk/openai"
|
||||
import { createOpenAICompatible } from "@ai-sdk/openai-compatible"
|
||||
import type { LanguageModelV2Usage, LanguageModelV2Prompt } from "@ai-sdk/provider"
|
||||
import type { LanguageModelV2Prompt } from "@ai-sdk/provider"
|
||||
import { type ChatCompletionCreateParamsBase } from "openai/resources/chat/completions"
|
||||
import { Actor } from "@opencode/cloud-core/actor.js"
|
||||
import { and, Database, eq, sql } from "@opencode/cloud-core/drizzle/index.js"
|
||||
@@ -178,469 +178,491 @@ const RestAuth: MiddlewareHandler = async (c, next) => {
|
||||
const app = new Hono<{ Bindings: Env; Variables: { keyRecord?: { id: string; workspaceID: string } } }>()
|
||||
.get("/", (c) => c.text("Hello, world!"))
|
||||
.post("/v1/chat/completions", GatewayAuth, async (c) => {
|
||||
try {
|
||||
const body = await c.req.json<ChatCompletionCreateParamsBase>()
|
||||
const keyRecord = c.get("keyRecord")!
|
||||
|
||||
console.log(body)
|
||||
|
||||
const model = SUPPORTED_MODELS[body.model as keyof typeof SUPPORTED_MODELS]?.model()
|
||||
if (!model) throw new Error(`Unsupported model: ${body.model}`)
|
||||
|
||||
const requestBody = transformOpenAIRequestToAiSDK()
|
||||
|
||||
return body.stream ? await handleStream() : await handleGenerate()
|
||||
|
||||
async function handleStream() {
|
||||
const result = await streamText({
|
||||
model,
|
||||
...requestBody,
|
||||
})
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
const id = `chatcmpl-${Date.now()}`
|
||||
const created = Math.floor(Date.now() / 1000)
|
||||
|
||||
try {
|
||||
for await (const chunk of result.fullStream) {
|
||||
// TODO
|
||||
//console.log("!!! CHUCK !!!", chunk);
|
||||
switch (chunk.type) {
|
||||
case "text-delta": {
|
||||
const data = {
|
||||
id,
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
content: chunk.text,
|
||||
},
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
}
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||
break
|
||||
}
|
||||
|
||||
case "reasoning-delta": {
|
||||
const data = {
|
||||
id,
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
reasoning_content: chunk.text,
|
||||
},
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
}
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||
break
|
||||
}
|
||||
|
||||
case "tool-call": {
|
||||
const data = {
|
||||
id,
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
tool_calls: [
|
||||
{
|
||||
id: chunk.toolCallId,
|
||||
type: "function",
|
||||
function: {
|
||||
name: chunk.toolName,
|
||||
arguments: JSON.stringify(chunk.input),
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
}
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||
break
|
||||
}
|
||||
|
||||
case "error": {
|
||||
const data = {
|
||||
id,
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: body.model,
|
||||
error: {
|
||||
message: chunk.error,
|
||||
type: "server_error",
|
||||
},
|
||||
}
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
|
||||
controller.close()
|
||||
break
|
||||
}
|
||||
|
||||
case "finish": {
|
||||
const finishReason =
|
||||
{
|
||||
stop: "stop",
|
||||
length: "length",
|
||||
"content-filter": "content_filter",
|
||||
"tool-calls": "tool_calls",
|
||||
error: "stop",
|
||||
other: "stop",
|
||||
unknown: "stop",
|
||||
}[chunk.finishReason] || "stop"
|
||||
|
||||
const data = {
|
||||
id,
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {},
|
||||
finish_reason: finishReason,
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
prompt_tokens: chunk.totalUsage.inputTokens,
|
||||
completion_tokens: chunk.totalUsage.outputTokens,
|
||||
total_tokens: chunk.totalUsage.totalTokens,
|
||||
completion_tokens_details: {
|
||||
reasoning_tokens: chunk.totalUsage.reasoningTokens,
|
||||
},
|
||||
prompt_tokens_details: {
|
||||
cached_tokens: chunk.totalUsage.cachedInputTokens,
|
||||
},
|
||||
},
|
||||
}
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
|
||||
controller.close()
|
||||
break
|
||||
}
|
||||
|
||||
//case "stream-start":
|
||||
//case "response-metadata":
|
||||
case "start-step":
|
||||
case "finish-step":
|
||||
case "text-start":
|
||||
case "text-end":
|
||||
case "reasoning-start":
|
||||
case "reasoning-end":
|
||||
case "tool-input-start":
|
||||
case "tool-input-delta":
|
||||
case "tool-input-end":
|
||||
case "raw":
|
||||
default:
|
||||
// Log unknown chunk types for debugging
|
||||
console.warn(`Unknown chunk type: ${(chunk as any).type}`)
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
controller.error(error)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async function handleGenerate() {
|
||||
const response = await generateText({
|
||||
model,
|
||||
...requestBody,
|
||||
})
|
||||
await trackUsage(body.model, response.usage)
|
||||
return c.json({
|
||||
id: `chatcmpl-${Date.now()}`,
|
||||
object: "chat.completion" as const,
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model: body.model,
|
||||
choices: [
|
||||
return await Actor.provide("system", { workspaceID: keyRecord.workspaceID }, async () => {
|
||||
try {
|
||||
// Check balance
|
||||
const customer = await Billing.get()
|
||||
if (customer.balance <= 0) {
|
||||
return c.json(
|
||||
{
|
||||
index: 0,
|
||||
message: {
|
||||
role: "assistant" as const,
|
||||
content: response.content?.find((c) => c.type === "text")?.text ?? "",
|
||||
reasoning_content: response.content?.find((c) => c.type === "reasoning")?.text,
|
||||
tool_calls: response.content
|
||||
?.filter((c) => c.type === "tool-call")
|
||||
.map((toolCall) => ({
|
||||
id: toolCall.toolCallId,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: toolCall.toolName,
|
||||
arguments: toolCall.input,
|
||||
},
|
||||
})),
|
||||
error: {
|
||||
message: "Insufficient balance",
|
||||
type: "insufficient_quota",
|
||||
param: null,
|
||||
code: "insufficient_quota",
|
||||
},
|
||||
finish_reason:
|
||||
(
|
||||
{
|
||||
stop: "stop",
|
||||
length: "length",
|
||||
"content-filter": "content_filter",
|
||||
"tool-calls": "tool_calls",
|
||||
error: "stop",
|
||||
other: "stop",
|
||||
unknown: "stop",
|
||||
} as const
|
||||
)[response.finishReason] || "stop",
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
prompt_tokens: response.usage?.inputTokens,
|
||||
completion_tokens: response.usage?.outputTokens,
|
||||
total_tokens: response.usage?.totalTokens,
|
||||
completion_tokens_details: {
|
||||
reasoning_tokens: response.usage?.reasoningTokens,
|
||||
},
|
||||
prompt_tokens_details: {
|
||||
cached_tokens: response.usage?.cachedInputTokens,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function transformOpenAIRequestToAiSDK() {
|
||||
const prompt = transformMessages()
|
||||
|
||||
return {
|
||||
prompt,
|
||||
maxOutputTokens: body.max_tokens ?? body.max_completion_tokens ?? undefined,
|
||||
temperature: body.temperature ?? undefined,
|
||||
topP: body.top_p ?? undefined,
|
||||
frequencyPenalty: body.frequency_penalty ?? undefined,
|
||||
presencePenalty: body.presence_penalty ?? undefined,
|
||||
providerOptions: body.reasoning_effort
|
||||
? {
|
||||
anthropic: {
|
||||
reasoningEffort: body.reasoning_effort,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
stopSequences: (typeof body.stop === "string" ? [body.stop] : body.stop) ?? undefined,
|
||||
responseFormat: (() => {
|
||||
if (!body.response_format) return { type: "text" }
|
||||
if (body.response_format.type === "json_schema")
|
||||
return {
|
||||
type: "json",
|
||||
schema: body.response_format.json_schema.schema,
|
||||
name: body.response_format.json_schema.name,
|
||||
description: body.response_format.json_schema.description,
|
||||
}
|
||||
if (body.response_format.type === "json_object") return { type: "json" }
|
||||
throw new Error("Unsupported response format")
|
||||
})(),
|
||||
seed: body.seed ?? undefined,
|
||||
401,
|
||||
)
|
||||
}
|
||||
|
||||
function transformTools() {
|
||||
const { tools, tool_choice } = body
|
||||
const body = await c.req.json<ChatCompletionCreateParamsBase>()
|
||||
const model = SUPPORTED_MODELS[body.model as keyof typeof SUPPORTED_MODELS]?.model()
|
||||
if (!model) throw new Error(`Unsupported model: ${body.model}`)
|
||||
|
||||
if (!tools || tools.length === 0) {
|
||||
return { tools: undefined, toolChoice: undefined }
|
||||
const requestBody = transformOpenAIRequestToAiSDK()
|
||||
|
||||
return body.stream ? await handleStream() : await handleGenerate()
|
||||
|
||||
async function handleStream() {
|
||||
const result = await model.doStream({
|
||||
...requestBody,
|
||||
})
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
const stream = new ReadableStream({
|
||||
async start(controller) {
|
||||
const id = `chatcmpl-${Date.now()}`
|
||||
const created = Math.floor(Date.now() / 1000)
|
||||
|
||||
try {
|
||||
for await (const chunk of result.stream) {
|
||||
console.log("!!! CHUNK !!! : " + chunk.type)
|
||||
switch (chunk.type) {
|
||||
case "text-delta": {
|
||||
const data = {
|
||||
id,
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
content: chunk.delta,
|
||||
},
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
}
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||
break
|
||||
}
|
||||
|
||||
case "reasoning-delta": {
|
||||
const data = {
|
||||
id,
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
reasoning_content: chunk.delta,
|
||||
},
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
}
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||
break
|
||||
}
|
||||
|
||||
case "tool-call": {
|
||||
const data = {
|
||||
id,
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
tool_calls: [
|
||||
{
|
||||
index: 0,
|
||||
id: chunk.toolCallId,
|
||||
type: "function",
|
||||
function: {
|
||||
name: chunk.toolName,
|
||||
arguments: chunk.input,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
}
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||
break
|
||||
}
|
||||
|
||||
case "error": {
|
||||
const data = {
|
||||
id,
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {},
|
||||
finish_reason: "stop",
|
||||
},
|
||||
],
|
||||
error: {
|
||||
message: typeof chunk.error === "string" ? chunk.error : chunk.error,
|
||||
type: "server_error",
|
||||
},
|
||||
}
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
|
||||
controller.close()
|
||||
break
|
||||
}
|
||||
|
||||
case "finish": {
|
||||
const data = {
|
||||
id,
|
||||
object: "chat.completion.chunk",
|
||||
created,
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {},
|
||||
finish_reason:
|
||||
{
|
||||
stop: "stop",
|
||||
length: "length",
|
||||
"content-filter": "content_filter",
|
||||
"tool-calls": "tool_calls",
|
||||
error: "stop",
|
||||
other: "stop",
|
||||
unknown: "stop",
|
||||
}[chunk.finishReason] || "stop",
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
prompt_tokens: chunk.usage.inputTokens,
|
||||
completion_tokens: chunk.usage.outputTokens,
|
||||
total_tokens: chunk.usage.totalTokens,
|
||||
completion_tokens_details: {
|
||||
reasoning_tokens: chunk.usage.reasoningTokens,
|
||||
},
|
||||
prompt_tokens_details: {
|
||||
cached_tokens: chunk.usage.cachedInputTokens,
|
||||
},
|
||||
},
|
||||
}
|
||||
await trackUsage(body.model, chunk.usage, chunk.providerMetadata)
|
||||
controller.enqueue(encoder.encode(`data: ${JSON.stringify(data)}\n\n`))
|
||||
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
|
||||
controller.close()
|
||||
break
|
||||
}
|
||||
|
||||
//case "stream-start":
|
||||
//case "response-metadata":
|
||||
case "text-start":
|
||||
case "text-end":
|
||||
case "reasoning-start":
|
||||
case "reasoning-end":
|
||||
case "tool-input-start":
|
||||
case "tool-input-delta":
|
||||
case "tool-input-end":
|
||||
case "raw":
|
||||
default:
|
||||
// Log unknown chunk types for debugging
|
||||
console.warn(`Unknown chunk type: ${(chunk as any).type}`)
|
||||
break
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
controller.error(error)
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async function handleGenerate() {
|
||||
const response = await model.doGenerate({
|
||||
...requestBody,
|
||||
})
|
||||
await trackUsage(body.model, response.usage, response.providerMetadata)
|
||||
return c.json({
|
||||
id: `chatcmpl-${Date.now()}`,
|
||||
object: "chat.completion" as const,
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
message: {
|
||||
role: "assistant" as const,
|
||||
content: response.content?.find((c) => c.type === "text")?.text ?? "",
|
||||
reasoning_content: response.content?.find((c) => c.type === "reasoning")?.text,
|
||||
tool_calls: response.content
|
||||
?.filter((c) => c.type === "tool-call")
|
||||
.map((toolCall) => ({
|
||||
id: toolCall.toolCallId,
|
||||
type: "function" as const,
|
||||
function: {
|
||||
name: toolCall.toolName,
|
||||
arguments: toolCall.input,
|
||||
},
|
||||
})),
|
||||
},
|
||||
finish_reason:
|
||||
(
|
||||
{
|
||||
stop: "stop",
|
||||
length: "length",
|
||||
"content-filter": "content_filter",
|
||||
"tool-calls": "tool_calls",
|
||||
error: "stop",
|
||||
other: "stop",
|
||||
unknown: "stop",
|
||||
} as const
|
||||
)[response.finishReason] || "stop",
|
||||
},
|
||||
],
|
||||
usage: {
|
||||
prompt_tokens: response.usage?.inputTokens,
|
||||
completion_tokens: response.usage?.outputTokens,
|
||||
total_tokens: response.usage?.totalTokens,
|
||||
completion_tokens_details: {
|
||||
reasoning_tokens: response.usage?.reasoningTokens,
|
||||
},
|
||||
prompt_tokens_details: {
|
||||
cached_tokens: response.usage?.cachedInputTokens,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function transformOpenAIRequestToAiSDK() {
|
||||
const prompt = transformMessages()
|
||||
const tools = transformTools()
|
||||
|
||||
return {
|
||||
prompt,
|
||||
maxOutputTokens: body.max_tokens ?? body.max_completion_tokens ?? undefined,
|
||||
temperature: body.temperature ?? undefined,
|
||||
topP: body.top_p ?? undefined,
|
||||
frequencyPenalty: body.frequency_penalty ?? undefined,
|
||||
presencePenalty: body.presence_penalty ?? undefined,
|
||||
providerOptions: body.reasoning_effort
|
||||
? {
|
||||
anthropic: {
|
||||
reasoningEffort: body.reasoning_effort,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
stopSequences: (typeof body.stop === "string" ? [body.stop] : body.stop) ?? undefined,
|
||||
responseFormat: (() => {
|
||||
if (!body.response_format) return { type: "text" as const }
|
||||
if (body.response_format.type === "json_schema")
|
||||
return {
|
||||
type: "json" as const,
|
||||
schema: body.response_format.json_schema.schema,
|
||||
name: body.response_format.json_schema.name,
|
||||
description: body.response_format.json_schema.description,
|
||||
}
|
||||
if (body.response_format.type === "json_object") return { type: "json" as const }
|
||||
throw new Error("Unsupported response format")
|
||||
})(),
|
||||
seed: body.seed ?? undefined,
|
||||
tools: tools.tools,
|
||||
toolChoice: tools.toolChoice,
|
||||
}
|
||||
|
||||
const aiSdkTools = tools.reduce(
|
||||
(acc, tool) => {
|
||||
acc[tool.function.name] = {
|
||||
type: "function" as const,
|
||||
function transformTools() {
|
||||
const { tools, tool_choice } = body
|
||||
|
||||
if (!tools || tools.length === 0) {
|
||||
return { tools: undefined, toolChoice: undefined }
|
||||
}
|
||||
|
||||
const aiSdkTools = tools.map((tool) => {
|
||||
return {
|
||||
type: tool.type,
|
||||
name: tool.function.name,
|
||||
description: tool.function.description,
|
||||
inputSchema: tool.function.parameters,
|
||||
inputSchema: tool.function.parameters!,
|
||||
}
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, any>,
|
||||
)
|
||||
})
|
||||
|
||||
let aiSdkToolChoice
|
||||
if (tool_choice == null) {
|
||||
aiSdkToolChoice = undefined
|
||||
} else if (tool_choice === "auto") {
|
||||
aiSdkToolChoice = "auto"
|
||||
} else if (tool_choice === "none") {
|
||||
aiSdkToolChoice = "none"
|
||||
} else if (tool_choice === "required") {
|
||||
aiSdkToolChoice = "required"
|
||||
} else if (tool_choice.type === "function") {
|
||||
aiSdkToolChoice = {
|
||||
type: "tool",
|
||||
toolName: tool_choice.function.name,
|
||||
let aiSdkToolChoice
|
||||
if (tool_choice == null) {
|
||||
aiSdkToolChoice = undefined
|
||||
} else if (tool_choice === "auto") {
|
||||
aiSdkToolChoice = { type: "auto" as const }
|
||||
} else if (tool_choice === "none") {
|
||||
aiSdkToolChoice = { type: "none" as const }
|
||||
} else if (tool_choice === "required") {
|
||||
aiSdkToolChoice = { type: "required" as const }
|
||||
} else if (tool_choice.type === "function") {
|
||||
aiSdkToolChoice = {
|
||||
type: "tool" as const,
|
||||
toolName: tool_choice.function.name,
|
||||
}
|
||||
}
|
||||
|
||||
return { tools: aiSdkTools, toolChoice: aiSdkToolChoice }
|
||||
}
|
||||
|
||||
return { tools: aiSdkTools, toolChoice: aiSdkToolChoice }
|
||||
}
|
||||
function transformMessages() {
|
||||
const { messages } = body
|
||||
const prompt: LanguageModelV2Prompt = []
|
||||
|
||||
function transformMessages() {
|
||||
const { messages } = body
|
||||
const prompt: LanguageModelV2Prompt = []
|
||||
|
||||
for (const message of messages) {
|
||||
switch (message.role) {
|
||||
case "system": {
|
||||
prompt.push({
|
||||
role: "system",
|
||||
content: message.content as string,
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case "user": {
|
||||
if (typeof message.content === "string") {
|
||||
for (const message of messages) {
|
||||
switch (message.role) {
|
||||
case "system": {
|
||||
prompt.push({
|
||||
role: "user",
|
||||
content: [{ type: "text", text: message.content }],
|
||||
})
|
||||
} else {
|
||||
const content = message.content.map((part) => {
|
||||
switch (part.type) {
|
||||
case "text":
|
||||
return { type: "text" as const, text: part.text }
|
||||
case "image_url":
|
||||
return {
|
||||
type: "file" as const,
|
||||
mediaType: "image/jpeg" as const,
|
||||
data: part.image_url.url,
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unsupported content part type: ${(part as any).type}`)
|
||||
}
|
||||
})
|
||||
prompt.push({
|
||||
role: "user",
|
||||
content,
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case "assistant": {
|
||||
const content: Array<
|
||||
| { type: "text"; text: string }
|
||||
| {
|
||||
type: "tool-call"
|
||||
toolCallId: string
|
||||
toolName: string
|
||||
input: any
|
||||
}
|
||||
> = []
|
||||
|
||||
if (message.content) {
|
||||
content.push({
|
||||
type: "text",
|
||||
text: message.content as string,
|
||||
role: "system",
|
||||
content: message.content as string,
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
if (message.tool_calls) {
|
||||
for (const toolCall of message.tool_calls) {
|
||||
content.push({
|
||||
type: "tool-call",
|
||||
toolCallId: toolCall.id,
|
||||
toolName: toolCall.function.name,
|
||||
input: JSON.parse(toolCall.function.arguments),
|
||||
case "user": {
|
||||
if (typeof message.content === "string") {
|
||||
prompt.push({
|
||||
role: "user",
|
||||
content: [{ type: "text", text: message.content }],
|
||||
})
|
||||
} else {
|
||||
const content = message.content.map((part) => {
|
||||
switch (part.type) {
|
||||
case "text":
|
||||
return { type: "text" as const, text: part.text }
|
||||
case "image_url":
|
||||
return {
|
||||
type: "file" as const,
|
||||
mediaType: "image/jpeg" as const,
|
||||
data: part.image_url.url,
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unsupported content part type: ${(part as any).type}`)
|
||||
}
|
||||
})
|
||||
prompt.push({
|
||||
role: "user",
|
||||
content,
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
prompt.push({
|
||||
role: "assistant",
|
||||
content,
|
||||
})
|
||||
break
|
||||
}
|
||||
case "assistant": {
|
||||
const content: Array<
|
||||
| { type: "text"; text: string }
|
||||
| {
|
||||
type: "tool-call"
|
||||
toolCallId: string
|
||||
toolName: string
|
||||
input: any
|
||||
}
|
||||
> = []
|
||||
|
||||
case "tool": {
|
||||
prompt.push({
|
||||
role: "tool",
|
||||
content: [
|
||||
{
|
||||
type: "tool-result",
|
||||
toolName: "placeholder",
|
||||
toolCallId: message.tool_call_id,
|
||||
output: {
|
||||
type: "text",
|
||||
value: message.content as string,
|
||||
if (message.content) {
|
||||
content.push({
|
||||
type: "text",
|
||||
text: message.content as string,
|
||||
})
|
||||
}
|
||||
|
||||
if (message.tool_calls) {
|
||||
for (const toolCall of message.tool_calls) {
|
||||
content.push({
|
||||
type: "tool-call",
|
||||
toolCallId: toolCall.id,
|
||||
toolName: toolCall.function.name,
|
||||
input: JSON.parse(toolCall.function.arguments),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
prompt.push({
|
||||
role: "assistant",
|
||||
content,
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
case "tool": {
|
||||
prompt.push({
|
||||
role: "tool",
|
||||
content: [
|
||||
{
|
||||
type: "tool-result",
|
||||
toolName: "placeholder",
|
||||
toolCallId: message.tool_call_id,
|
||||
output: {
|
||||
type: "text",
|
||||
value: message.content as string,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
break
|
||||
}
|
||||
],
|
||||
})
|
||||
break
|
||||
}
|
||||
|
||||
default: {
|
||||
throw new Error(`Unsupported message role: ${message.role}`)
|
||||
default: {
|
||||
throw new Error(`Unsupported message role: ${message.role}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return prompt
|
||||
}
|
||||
|
||||
return prompt
|
||||
}
|
||||
}
|
||||
|
||||
async function trackUsage(model: string, usage: LanguageModelV2Usage) {
|
||||
const keyRecord = c.get("keyRecord")
|
||||
if (!keyRecord) return
|
||||
async function trackUsage(model: string, usage: LanguageModelUsage, providerMetadata?: ProviderMetadata) {
|
||||
const modelData = SUPPORTED_MODELS[model as keyof typeof SUPPORTED_MODELS]
|
||||
if (!modelData) throw new Error(`Unsupported model: ${model}`)
|
||||
|
||||
const modelData = SUPPORTED_MODELS[model as keyof typeof SUPPORTED_MODELS]
|
||||
if (!modelData) throw new Error(`Unsupported model: ${model}`)
|
||||
const inputTokens = usage.inputTokens ?? 0
|
||||
const outputTokens = usage.outputTokens ?? 0
|
||||
const reasoningTokens = usage.reasoningTokens ?? 0
|
||||
const cacheReadTokens = usage.cachedInputTokens ?? 0
|
||||
const cacheWriteTokens =
|
||||
providerMetadata?.["anthropic"]?.["cacheCreationInputTokens"] ??
|
||||
// @ts-expect-error
|
||||
providerMetadata?.["bedrock"]?.["usage"]?.["cacheWriteInputTokens"] ??
|
||||
0
|
||||
|
||||
const inputCost = modelData.input * (usage.inputTokens ?? 0)
|
||||
const outputCost = modelData.output * (usage.outputTokens ?? 0)
|
||||
const reasoningCost = modelData.reasoning * (usage.reasoningTokens ?? 0)
|
||||
const cacheReadCost = modelData.cacheRead * (usage.cachedInputTokens ?? 0)
|
||||
const cacheWriteCost = modelData.cacheWrite * (usage.outputTokens ?? 0)
|
||||
const inputCost = modelData.input * inputTokens
|
||||
const outputCost = modelData.output * outputTokens
|
||||
const reasoningCost = modelData.reasoning * reasoningTokens
|
||||
const cacheReadCost = modelData.cacheRead * cacheReadTokens
|
||||
const cacheWriteCost = modelData.cacheWrite * cacheWriteTokens
|
||||
const costInCents = (inputCost + outputCost + reasoningCost + cacheReadCost + cacheWriteCost) * 100
|
||||
|
||||
const totalCost = inputCost + outputCost + reasoningCost + cacheReadCost + cacheWriteCost
|
||||
|
||||
await Actor.provide("system", { workspaceID: keyRecord.workspaceID }, async () => {
|
||||
await Billing.consume({
|
||||
model,
|
||||
inputTokens: usage.inputTokens ?? 0,
|
||||
outputTokens: usage.outputTokens ?? 0,
|
||||
reasoningTokens: usage.reasoningTokens ?? 0,
|
||||
cacheReadTokens: usage.cachedInputTokens ?? 0,
|
||||
cacheWriteTokens: usage.outputTokens ?? 0,
|
||||
costInCents: totalCost * 100,
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
reasoningTokens,
|
||||
cacheReadTokens,
|
||||
cacheWriteTokens,
|
||||
costInCents,
|
||||
})
|
||||
})
|
||||
|
||||
await Database.use((tx) =>
|
||||
tx
|
||||
.update(KeyTable)
|
||||
.set({ timeUsed: sql`now()` })
|
||||
.where(eq(KeyTable.id, keyRecord.id)),
|
||||
)
|
||||
await Database.use((tx) =>
|
||||
tx
|
||||
.update(KeyTable)
|
||||
.set({ timeUsed: sql`now()` })
|
||||
.where(eq(KeyTable.id, keyRecord.id)),
|
||||
)
|
||||
}
|
||||
} catch (error: any) {
|
||||
return c.json({ error: { message: error.message } }, 500)
|
||||
}
|
||||
} catch (error: any) {
|
||||
return c.json({ error: { message: error.message } }, 500)
|
||||
}
|
||||
})
|
||||
})
|
||||
.use("/*", cors())
|
||||
.use(RestAuth)
|
||||
@@ -699,7 +721,7 @@ const app = new Hono<{ Bindings: Env; Variables: { keyRecord?: { id: string; wor
|
||||
price_data: {
|
||||
currency: "usd",
|
||||
product_data: {
|
||||
name: "OpenControl credits",
|
||||
name: "opencode credits",
|
||||
},
|
||||
unit_amount: 2000, // $20 minimum
|
||||
},
|
||||
|
||||
Vendored
+4
@@ -50,6 +50,10 @@ declare module "sst" {
|
||||
"type": "sst.sst.Secret"
|
||||
"value": string
|
||||
}
|
||||
"GOOGLE_CLIENT_ID": {
|
||||
"type": "sst.sst.Secret"
|
||||
"value": string
|
||||
}
|
||||
"OPENAI_API_KEY": {
|
||||
"type": "sst.sst.Secret"
|
||||
"value": string
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode/cloud-web",
|
||||
"version": "0.0.0",
|
||||
"version": "0.4.22",
|
||||
"private": true,
|
||||
"description": "",
|
||||
"type": "module",
|
||||
|
||||
@@ -24,9 +24,12 @@ export default function Index() {
|
||||
</section>
|
||||
|
||||
<section data-slot="cta">
|
||||
<div data-slot="col-2">
|
||||
<div>
|
||||
<span onClick={() => auth.authorize({ provider: "github" })}>Sign in with GitHub</span>
|
||||
</div>
|
||||
<div>
|
||||
<span onClick={() => auth.authorize({ provider: "google" })}>Sign in with Google</span>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -80,90 +80,4 @@
|
||||
border-left: 2px solid var(--color-border);
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="images"] {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: stretch;
|
||||
justify-content: space-between;
|
||||
border-top: 2px solid var(--color-border);
|
||||
|
||||
& > div {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: calc(var(--padding) / 4);
|
||||
padding: calc(var(--padding) / 2);
|
||||
border-width: 0;
|
||||
border-style: solid;
|
||||
border-color: var(--color-border);
|
||||
|
||||
& > div, a {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
}
|
||||
|
||||
p {
|
||||
letter-spacing: -0.03125rem;
|
||||
text-transform: uppercase;
|
||||
color: var(--color-text-dimmed);
|
||||
}
|
||||
|
||||
& > div + div {
|
||||
border-width: 0 0 0 2px;
|
||||
}
|
||||
|
||||
@media (max-width: 30rem) {
|
||||
& {
|
||||
flex-direction: column;
|
||||
}
|
||||
& > div + div {
|
||||
border-width: 2px 0 0 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[data-slot="content"] {
|
||||
border-top: 2px solid var(--color-border);
|
||||
padding: var(--padding);
|
||||
|
||||
& > p {
|
||||
line-height: var(--font-line-height);
|
||||
}
|
||||
|
||||
ol {
|
||||
margin-top: calc(var(--vertical-padding) / 2);
|
||||
padding-left: 2.5rem;
|
||||
list-style-type: decimal;
|
||||
line-height: var(--font-line-height);
|
||||
|
||||
& > li + li {
|
||||
margin-top: calc(var(--vertical-padding) / 2);
|
||||
}
|
||||
|
||||
& > li b {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
[data-slot="footer"] {
|
||||
border-top: 2px solid var(--color-border);
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
|
||||
& > div {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
text-transform: uppercase;
|
||||
padding: calc(var(--padding) / 2) 0.5rem;
|
||||
}
|
||||
|
||||
& > div + div {
|
||||
border-left: 2px solid var(--color-border);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+48
-32
@@ -2,6 +2,50 @@ import { WebhookEndpoint } from "pulumi-stripe"
|
||||
import { domain } from "./stage"
|
||||
import { web } from "./app"
|
||||
|
||||
////////////////
|
||||
// DATABASE
|
||||
////////////////
|
||||
|
||||
const DATABASE_USERNAME = new sst.Secret("DATABASE_USERNAME")
|
||||
const DATABASE_PASSWORD = new sst.Secret("DATABASE_PASSWORD")
|
||||
export const database = new sst.Linkable("Database", {
|
||||
properties: {
|
||||
host: "aws-us-east-2-1.pg.psdb.cloud",
|
||||
database: "postgres",
|
||||
username: DATABASE_USERNAME.value,
|
||||
password: DATABASE_PASSWORD.value,
|
||||
port: 5432,
|
||||
},
|
||||
})
|
||||
|
||||
new sst.x.DevCommand("Studio", {
|
||||
link: [database],
|
||||
dev: {
|
||||
command: "bun db studio",
|
||||
directory: "cloud/core",
|
||||
autostart: true,
|
||||
},
|
||||
})
|
||||
|
||||
////////////////
|
||||
// AUTH
|
||||
////////////////
|
||||
|
||||
const GITHUB_CLIENT_ID_CONSOLE = new sst.Secret("GITHUB_CLIENT_ID_CONSOLE")
|
||||
const GITHUB_CLIENT_SECRET_CONSOLE = new sst.Secret("GITHUB_CLIENT_SECRET_CONSOLE")
|
||||
const GOOGLE_CLIENT_ID = new sst.Secret("GOOGLE_CLIENT_ID")
|
||||
const authStorage = new sst.cloudflare.Kv("AuthStorage")
|
||||
export const auth = new sst.cloudflare.Worker("AuthApi", {
|
||||
domain: `auth.${domain}`,
|
||||
handler: "cloud/function/src/auth.ts",
|
||||
url: true,
|
||||
link: [database, authStorage, GITHUB_CLIENT_ID_CONSOLE, GITHUB_CLIENT_SECRET_CONSOLE, GOOGLE_CLIENT_ID],
|
||||
})
|
||||
|
||||
////////////////
|
||||
// GATEWAY
|
||||
////////////////
|
||||
|
||||
export const stripeWebhook = new WebhookEndpoint("StripeWebhook", {
|
||||
url: $interpolate`https://api.gateway.${domain}/stripe/webhook`,
|
||||
enabledEvents: [
|
||||
@@ -33,41 +77,9 @@ export const stripeWebhook = new WebhookEndpoint("StripeWebhook", {
|
||||
],
|
||||
})
|
||||
|
||||
const DATABASE_USERNAME = new sst.Secret("DATABASE_USERNAME")
|
||||
const DATABASE_PASSWORD = new sst.Secret("DATABASE_PASSWORD")
|
||||
export const database = new sst.Linkable("Database", {
|
||||
properties: {
|
||||
host: "aws-us-east-2-1.pg.psdb.cloud",
|
||||
database: "postgres",
|
||||
username: DATABASE_USERNAME.value,
|
||||
password: DATABASE_PASSWORD.value,
|
||||
port: 5432,
|
||||
},
|
||||
})
|
||||
|
||||
new sst.x.DevCommand("Studio", {
|
||||
link: [database],
|
||||
dev: {
|
||||
command: "bun db studio",
|
||||
directory: "cloud/core",
|
||||
autostart: true,
|
||||
},
|
||||
})
|
||||
|
||||
const GITHUB_CLIENT_ID_CONSOLE = new sst.Secret("GITHUB_CLIENT_ID_CONSOLE")
|
||||
const GITHUB_CLIENT_SECRET_CONSOLE = new sst.Secret("GITHUB_CLIENT_SECRET_CONSOLE")
|
||||
const authStorage = new sst.cloudflare.Kv("AuthStorage")
|
||||
export const auth = new sst.cloudflare.Worker("AuthApi", {
|
||||
domain: `auth.${domain}`,
|
||||
handler: "cloud/function/src/auth.ts",
|
||||
url: true,
|
||||
link: [database, authStorage, GITHUB_CLIENT_ID_CONSOLE, GITHUB_CLIENT_SECRET_CONSOLE],
|
||||
})
|
||||
|
||||
const ANTHROPIC_API_KEY = new sst.Secret("ANTHROPIC_API_KEY")
|
||||
const OPENAI_API_KEY = new sst.Secret("OPENAI_API_KEY")
|
||||
const ZHIPU_API_KEY = new sst.Secret("ZHIPU_API_KEY")
|
||||
|
||||
const STRIPE_SECRET_KEY = new sst.Secret("STRIPE_SECRET_KEY")
|
||||
const AUTH_API_URL = new sst.Linkable("AUTH_API_URL", {
|
||||
properties: { value: auth.url.apply((url) => url!) },
|
||||
@@ -90,6 +102,10 @@ export const gateway = new sst.cloudflare.Worker("GatewayApi", {
|
||||
],
|
||||
})
|
||||
|
||||
////////////////
|
||||
// CONSOLE
|
||||
////////////////
|
||||
|
||||
export const console = new sst.cloudflare.x.StaticSite("Console", {
|
||||
domain: `console.${domain}`,
|
||||
path: "cloud/web",
|
||||
|
||||
@@ -1,25 +1,5 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"provider": {
|
||||
"oc-frank": {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": "OC-Frank",
|
||||
"options": {
|
||||
"baseURL": "https://api.gateway.frank.dev.opencode.ai/v1"
|
||||
},
|
||||
"models": {
|
||||
"anthropic/claude-sonnet-4": {
|
||||
"name": "Claude Sonnet 4"
|
||||
},
|
||||
"openai/gpt-4.1": {
|
||||
"name": "GPT-4.1"
|
||||
},
|
||||
"zhipuai/glm-4.5-flash": {
|
||||
"name": "GLM-4.5 Flash"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"mcp": {
|
||||
"context7": {
|
||||
"type": "remote",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode/function",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.22",
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
Vendored
+4
@@ -50,6 +50,10 @@ declare module "sst" {
|
||||
"type": "sst.sst.Secret"
|
||||
"value": string
|
||||
}
|
||||
"GOOGLE_CLIENT_ID": {
|
||||
"type": "sst.sst.Secret"
|
||||
"value": string
|
||||
}
|
||||
"OPENAI_API_KEY": {
|
||||
"type": "sst.sst.Secret"
|
||||
"value": string
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.22",
|
||||
"name": "opencode",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
@@ -16,7 +16,6 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ai-sdk/amazon-bedrock": "2.2.10",
|
||||
"@ai-sdk/anthropic": "1.2.12",
|
||||
"@octokit/webhooks-types": "7.6.1",
|
||||
"@standard-schema/spec": "1.0.0",
|
||||
"@tsconfig/bun": "1.0.7",
|
||||
|
||||
@@ -39,6 +39,14 @@ for (const [os, arch] of targets) {
|
||||
"../tui",
|
||||
)
|
||||
await $`bun build --define OPENCODE_TUI_PATH="'../../../dist/${name}/bin/tui'" --define OPENCODE_VERSION="'${version}'" --compile --target=bun-${os}-${arch} --outfile=dist/${name}/bin/opencode ./src/index.ts`
|
||||
// Run the binary only if it matches current OS/arch
|
||||
if (
|
||||
process.platform === (os === "windows" ? "win32" : os) &&
|
||||
(process.arch === arch || (process.arch === "x64" && arch === "x64-baseline"))
|
||||
) {
|
||||
console.log(`smoke test: running dist/${name}/bin/opencode --version`)
|
||||
await $`./dist/${name}/bin/opencode --version`
|
||||
}
|
||||
await $`rm -rf ./dist/${name}/bin/tui`
|
||||
await Bun.file(`dist/${name}/package.json`).write(
|
||||
JSON.stringify(
|
||||
@@ -79,44 +87,10 @@ await Bun.file(`./dist/${pkg.name}/package.json`).write(
|
||||
if (!dry) await $`cd ./dist/${pkg.name} && bun publish --access public --tag ${npmTag}`
|
||||
|
||||
if (!snapshot) {
|
||||
// Github Release
|
||||
for (const key of Object.keys(optionalDependencies)) {
|
||||
await $`cd dist/${key}/bin && zip -r ../../${key}.zip *`
|
||||
}
|
||||
|
||||
const previous = await fetch("https://api.github.com/repos/sst/opencode/releases/latest")
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error(res.statusText)
|
||||
return res.json()
|
||||
})
|
||||
.then((data) => data.tag_name)
|
||||
|
||||
console.log("finding commits between", previous, "and", "HEAD")
|
||||
const commits = await fetch(`https://api.github.com/repos/sst/opencode/compare/${previous}...HEAD`)
|
||||
.then((res) => res.json())
|
||||
.then((data) => data.commits || [])
|
||||
|
||||
const raw = commits.map((commit: any) => `- ${commit.commit.message.split("\n").join(" ")}`)
|
||||
console.log(raw)
|
||||
|
||||
const notes =
|
||||
raw
|
||||
.filter((x: string) => {
|
||||
const lower = x.toLowerCase()
|
||||
return (
|
||||
!lower.includes("release:") &&
|
||||
!lower.includes("ignore:") &&
|
||||
!lower.includes("chore:") &&
|
||||
!lower.includes("ci:") &&
|
||||
!lower.includes("wip:") &&
|
||||
!lower.includes("docs:") &&
|
||||
!lower.includes("doc:")
|
||||
)
|
||||
})
|
||||
.join("\n") || "No notable changes"
|
||||
|
||||
if (!dry) await $`gh release create v${version} --title "v${version}" --notes ${notes} ./dist/*.zip`
|
||||
|
||||
// Calculate SHA values
|
||||
const arm64Sha = await $`sha256sum ./dist/opencode-linux-arm64.zip | cut -d' ' -f1`.text().then((x) => x.trim())
|
||||
const x64Sha = await $`sha256sum ./dist/opencode-linux-x64.zip | cut -d' ' -f1`.text().then((x) => x.trim())
|
||||
|
||||
@@ -22,6 +22,7 @@ export namespace Agent {
|
||||
.optional(),
|
||||
prompt: z.string().optional(),
|
||||
tools: z.record(z.boolean()),
|
||||
options: z.record(z.string(), z.any()),
|
||||
})
|
||||
.openapi({
|
||||
ref: "Agent",
|
||||
@@ -39,15 +40,18 @@ export namespace Agent {
|
||||
todoread: false,
|
||||
todowrite: false,
|
||||
},
|
||||
options: {},
|
||||
mode: "subagent",
|
||||
},
|
||||
build: {
|
||||
name: "build",
|
||||
tools: {},
|
||||
options: {},
|
||||
mode: "primary",
|
||||
},
|
||||
plan: {
|
||||
name: "plan",
|
||||
options: {},
|
||||
tools: {
|
||||
write: false,
|
||||
edit: false,
|
||||
@@ -66,8 +70,14 @@ export namespace Agent {
|
||||
item = result[key] = {
|
||||
name: key,
|
||||
mode: "all",
|
||||
options: {},
|
||||
tools: {},
|
||||
}
|
||||
const { model, prompt, tools, description, temperature, top_p, mode, ...extra } = value
|
||||
item.options = {
|
||||
...item.options,
|
||||
...extra,
|
||||
}
|
||||
if (value.model) item.model = Provider.parseModel(value.model)
|
||||
if (value.prompt) item.prompt = value.prompt
|
||||
if (value.tools)
|
||||
|
||||
@@ -39,7 +39,7 @@ const AgentCreateCommand = cmd({
|
||||
const query = await prompts.text({
|
||||
message: "Description",
|
||||
placeholder: "What should this agent do?",
|
||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
||||
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||
})
|
||||
if (prompts.isCancel(query)) throw new UI.CancelledError()
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ export const AuthLoginCommand = cmd({
|
||||
if (provider === "other") {
|
||||
provider = await prompts.text({
|
||||
message: "Enter provider id",
|
||||
validate: (x) => x && (x.match(/^[0-9a-z-]+$/) ? undefined : "a-z, 0-9 and hyphens only"),
|
||||
validate: (x) => (x && x.match(/^[0-9a-z-]+$/) ? undefined : "a-z, 0-9 and hyphens only"),
|
||||
})
|
||||
if (prompts.isCancel(provider)) throw new UI.CancelledError()
|
||||
provider = provider.replace(/^@ai-sdk\//, "")
|
||||
@@ -193,7 +193,7 @@ export const AuthLoginCommand = cmd({
|
||||
|
||||
const code = await prompts.text({
|
||||
message: "Paste the authorization code here: ",
|
||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
||||
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||
})
|
||||
if (prompts.isCancel(code)) throw new UI.CancelledError()
|
||||
|
||||
@@ -229,7 +229,7 @@ export const AuthLoginCommand = cmd({
|
||||
|
||||
const code = await prompts.text({
|
||||
message: "Paste the authorization code here: ",
|
||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
||||
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||
})
|
||||
if (prompts.isCancel(code)) throw new UI.CancelledError()
|
||||
|
||||
@@ -302,7 +302,7 @@ export const AuthLoginCommand = cmd({
|
||||
|
||||
const key = await prompts.password({
|
||||
message: "Enter your API key",
|
||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
||||
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||
})
|
||||
if (prompts.isCancel(key)) throw new UI.CancelledError()
|
||||
await Auth.set(provider, {
|
||||
|
||||
@@ -19,7 +19,7 @@ export const McpAddCommand = cmd({
|
||||
|
||||
const name = await prompts.text({
|
||||
message: "Enter MCP server name",
|
||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
||||
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||
})
|
||||
if (prompts.isCancel(name)) throw new UI.CancelledError()
|
||||
|
||||
@@ -44,7 +44,7 @@ export const McpAddCommand = cmd({
|
||||
const command = await prompts.text({
|
||||
message: "Enter command to run",
|
||||
placeholder: "e.g., opencode x @modelcontextprotocol/server-filesystem",
|
||||
validate: (x) => x && (x.length > 0 ? undefined : "Required"),
|
||||
validate: (x) => (x && x.length > 0 ? undefined : "Required"),
|
||||
})
|
||||
if (prompts.isCancel(command)) throw new UI.CancelledError()
|
||||
|
||||
|
||||
@@ -84,10 +84,6 @@ export const RunCommand = cmd({
|
||||
return
|
||||
}
|
||||
|
||||
UI.empty()
|
||||
UI.println(UI.logo())
|
||||
UI.empty()
|
||||
|
||||
const cfg = await Config.get()
|
||||
if (cfg.share === "auto" || Flag.OPENCODE_AUTO_SHARE || args.share) {
|
||||
try {
|
||||
@@ -101,7 +97,6 @@ export const RunCommand = cmd({
|
||||
}
|
||||
}
|
||||
}
|
||||
UI.empty()
|
||||
|
||||
const agent = await (async () => {
|
||||
if (args.agent) return Agent.get(args.agent)
|
||||
@@ -116,9 +111,6 @@ export const RunCommand = cmd({
|
||||
return Provider.defaultModel()
|
||||
})()
|
||||
|
||||
UI.println(UI.Style.TEXT_NORMAL_BOLD + "@ ", UI.Style.TEXT_NORMAL + `${providerID}/${modelID}`)
|
||||
UI.empty()
|
||||
|
||||
function printEvent(color: string, type: string, title: string) {
|
||||
UI.println(
|
||||
color + `|`,
|
||||
@@ -137,7 +129,8 @@ export const RunCommand = cmd({
|
||||
if (part.type === "tool" && part.state.status === "completed") {
|
||||
const [tool, color] = TOOL[part.tool] ?? [part.tool, UI.Style.TEXT_INFO_BOLD]
|
||||
const title =
|
||||
part.state.title || Object.keys(part.state.input).length > 0 ? JSON.stringify(part.state.input) : "Unknown"
|
||||
part.state.title ||
|
||||
(Object.keys(part.state.input).length > 0 ? JSON.stringify(part.state.input) : "Unknown")
|
||||
printEvent(color, tool, title)
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@ import { Log } from "../../util/log"
|
||||
import { FileWatcher } from "../../file/watch"
|
||||
import { Ide } from "../../ide"
|
||||
import { Agent } from "../../agent/agent"
|
||||
import { Flag } from "../../flag/flag"
|
||||
import { Session } from "../../session"
|
||||
|
||||
declare global {
|
||||
const OPENCODE_TUI_PATH: string
|
||||
@@ -38,6 +40,16 @@ export const TuiCommand = cmd({
|
||||
alias: ["m"],
|
||||
describe: "model to use in the format of provider/model",
|
||||
})
|
||||
.option("continue", {
|
||||
alias: ["c"],
|
||||
describe: "continue the last session",
|
||||
type: "boolean",
|
||||
})
|
||||
.option("session", {
|
||||
alias: ["s"],
|
||||
describe: "session id to continue",
|
||||
type: "string",
|
||||
})
|
||||
.option("prompt", {
|
||||
alias: ["p"],
|
||||
type: "string",
|
||||
@@ -68,6 +80,19 @@ export const TuiCommand = cmd({
|
||||
return
|
||||
}
|
||||
const result = await bootstrap({ cwd }, async (app) => {
|
||||
const sessionID = await (async () => {
|
||||
if (args.continue) {
|
||||
const list = Session.list()
|
||||
const first = await list.next()
|
||||
await list.return()
|
||||
if (first.done) return
|
||||
return first.value.id
|
||||
}
|
||||
if (args.session) {
|
||||
return args.session
|
||||
}
|
||||
return undefined
|
||||
})()
|
||||
FileWatcher.init()
|
||||
const providers = await Provider.list()
|
||||
if (Object.keys(providers).length === 0) {
|
||||
@@ -105,6 +130,7 @@ export const TuiCommand = cmd({
|
||||
...(args.model ? ["--model", args.model] : []),
|
||||
...(args.prompt ? ["--prompt", args.prompt] : []),
|
||||
...(args.mode ? ["--mode", args.mode] : []),
|
||||
...(sessionID ? ["--session", sessionID] : []),
|
||||
],
|
||||
cwd,
|
||||
stdout: "inherit",
|
||||
@@ -126,7 +152,7 @@ export const TuiCommand = cmd({
|
||||
if (Installation.isDev()) return
|
||||
if (Installation.isSnapshot()) return
|
||||
const config = await Config.global()
|
||||
if (config.autoupdate === false) return
|
||||
if (config.autoupdate === false || Flag.OPENCODE_DISABLE_AUTOUPDATE) return
|
||||
const latest = await Installation.latest().catch(() => {})
|
||||
if (!latest) return
|
||||
if (Installation.VERSION === latest) return
|
||||
|
||||
@@ -175,6 +175,7 @@ export namespace Config {
|
||||
description: z.string().optional().describe("Description of when to use the agent"),
|
||||
mode: z.union([z.literal("subagent"), z.literal("primary"), z.literal("all")]).optional(),
|
||||
})
|
||||
.catchall(z.any())
|
||||
.openapi({
|
||||
ref: "AgentConfig",
|
||||
})
|
||||
@@ -201,6 +202,7 @@ export namespace Config {
|
||||
session_interrupt: z.string().optional().default("esc").describe("Interrupt current session"),
|
||||
session_compact: z.string().optional().default("<leader>c").describe("Compact the session"),
|
||||
tool_details: z.string().optional().default("<leader>d").describe("Toggle tool details"),
|
||||
thinking_blocks: z.string().optional().default("<leader>b").describe("Toggle thinking blocks"),
|
||||
model_list: z.string().optional().default("<leader>m").describe("List available models"),
|
||||
theme_list: z.string().optional().default("<leader>t").describe("List available themes"),
|
||||
file_list: z.string().optional().default("<leader>f").describe("List files"),
|
||||
@@ -293,7 +295,7 @@ export namespace Config {
|
||||
.record(
|
||||
ModelsDev.Provider.partial()
|
||||
.extend({
|
||||
models: z.record(ModelsDev.Model.partial()),
|
||||
models: z.record(ModelsDev.Model.partial()).optional(),
|
||||
options: z
|
||||
.object({
|
||||
apiKey: z.string().optional(),
|
||||
@@ -341,6 +343,7 @@ export namespace Config {
|
||||
.object({
|
||||
edit: Permission.optional(),
|
||||
bash: z.union([Permission, z.record(z.string(), Permission)]).optional(),
|
||||
webfetch: Permission.optional(),
|
||||
})
|
||||
.optional(),
|
||||
experimental: z
|
||||
|
||||
@@ -2,6 +2,7 @@ export namespace Flag {
|
||||
export const OPENCODE_AUTO_SHARE = truthy("OPENCODE_AUTO_SHARE")
|
||||
export const OPENCODE_DISABLE_WATCHER = truthy("OPENCODE_DISABLE_WATCHER")
|
||||
export const OPENCODE_CONFIG = process.env["OPENCODE_CONFIG"]
|
||||
export const OPENCODE_DISABLE_AUTOUPDATE = truthy("OPENCODE_DISABLE_AUTOUPDATE")
|
||||
|
||||
function truthy(key: string) {
|
||||
const value = process.env[key]?.toLowerCase()
|
||||
|
||||
@@ -76,7 +76,7 @@ export const prettier: Info = {
|
||||
|
||||
export const biome: Info = {
|
||||
name: "biome",
|
||||
command: [BunProc.which(), "x", "biome", "format", "--write", "$FILE"],
|
||||
command: [BunProc.which(), "x", "@biomejs/biome", "format", "--write", "$FILE"],
|
||||
environment: {
|
||||
BUN_BE_BUN: "1",
|
||||
},
|
||||
@@ -110,8 +110,14 @@ export const biome: Info = {
|
||||
],
|
||||
async enabled() {
|
||||
const app = App.info()
|
||||
const items = await Filesystem.findUp("biome.json", app.path.cwd, app.path.root)
|
||||
return items.length > 0
|
||||
const configs = ["biome.json", "biome.jsonc"]
|
||||
for (const config of configs) {
|
||||
const found = await Filesystem.findUp(config, app.path.cwd, app.path.root)
|
||||
if (found.length > 0) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ await Promise.all([
|
||||
fs.mkdir(Global.Path.log, { recursive: true }),
|
||||
])
|
||||
|
||||
const CACHE_VERSION = "5"
|
||||
const CACHE_VERSION = "6"
|
||||
|
||||
const version = await Bun.file(path.join(Global.Path.cache, "version"))
|
||||
.text()
|
||||
|
||||
@@ -58,6 +58,8 @@ const cli = yargs(hideBin(process.argv))
|
||||
})(),
|
||||
})
|
||||
|
||||
process.env["OPENCODE"] = "1"
|
||||
|
||||
Log.Default.info("opencode", {
|
||||
version: Installation.VERSION,
|
||||
args: process.argv.slice(2),
|
||||
|
||||
@@ -65,6 +65,66 @@ export namespace LSPServer {
|
||||
},
|
||||
}
|
||||
|
||||
export const ESLint: Info = {
|
||||
id: "eslint",
|
||||
root: NearestRoot([
|
||||
"eslint.config.js",
|
||||
"eslint.config.mjs",
|
||||
"eslint.config.cjs",
|
||||
"eslint.config.ts",
|
||||
"eslint.config.mts",
|
||||
"eslint.config.cts",
|
||||
".eslintrc.js",
|
||||
".eslintrc.cjs",
|
||||
".eslintrc.yaml",
|
||||
".eslintrc.yml",
|
||||
".eslintrc.json",
|
||||
"package.json",
|
||||
]),
|
||||
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],
|
||||
async spawn(app, root) {
|
||||
const eslint = await Bun.resolve("eslint", app.path.cwd).catch(() => {})
|
||||
if (!eslint) return
|
||||
const serverPath = path.join(Global.Path.bin, "vscode-eslint", "server", "out", "eslintServer.js")
|
||||
if (!(await Bun.file(serverPath).exists())) {
|
||||
log.info("downloading and building VS Code ESLint server")
|
||||
const response = await fetch("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip")
|
||||
if (!response.ok) return
|
||||
|
||||
const zipPath = path.join(Global.Path.bin, "vscode-eslint.zip")
|
||||
await Bun.file(zipPath).write(response)
|
||||
|
||||
await $`unzip -o -q ${zipPath}`.cwd(Global.Path.bin).nothrow()
|
||||
await fs.rm(zipPath, { force: true })
|
||||
|
||||
const extractedPath = path.join(Global.Path.bin, "vscode-eslint-main")
|
||||
const finalPath = path.join(Global.Path.bin, "vscode-eslint")
|
||||
|
||||
if (await Bun.file(finalPath).exists()) {
|
||||
await fs.rm(finalPath, { force: true, recursive: true })
|
||||
}
|
||||
await fs.rename(extractedPath, finalPath)
|
||||
|
||||
await $`npm install`.cwd(finalPath).quiet()
|
||||
await $`npm run compile`.cwd(finalPath).quiet()
|
||||
|
||||
log.info("installed VS Code ESLint server", { serverPath })
|
||||
}
|
||||
|
||||
const proc = spawn(BunProc.which(), ["--max-old-space-size=8192", serverPath, "--stdio"], {
|
||||
cwd: root,
|
||||
env: {
|
||||
...process.env,
|
||||
BUN_BE_BUN: "1",
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
process: proc,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export const Gopls: Info = {
|
||||
id: "golang",
|
||||
root: async (file, app) => {
|
||||
@@ -361,4 +421,81 @@ export namespace LSPServer {
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
export const Clangd: Info = {
|
||||
id: "clangd",
|
||||
root: NearestRoot(["compile_commands.json", "compile_flags.txt", ".clangd", "CMakeLists.txt", "Makefile"]),
|
||||
extensions: [".c", ".cpp", ".cc", ".cxx", ".c++", ".h", ".hpp", ".hh", ".hxx", ".h++"],
|
||||
async spawn(_, root) {
|
||||
let bin = Bun.which("clangd", {
|
||||
PATH: process.env["PATH"] + ":" + Global.Path.bin,
|
||||
})
|
||||
if (!bin) {
|
||||
log.info("downloading clangd from GitHub releases")
|
||||
|
||||
const releaseResponse = await fetch("https://api.github.com/repos/clangd/clangd/releases/latest")
|
||||
if (!releaseResponse.ok) {
|
||||
log.error("Failed to fetch clangd release info")
|
||||
return
|
||||
}
|
||||
|
||||
const release = await releaseResponse.json()
|
||||
|
||||
const platform = process.platform
|
||||
let assetName = ""
|
||||
|
||||
if (platform === "darwin") {
|
||||
assetName = "clangd-mac-"
|
||||
} else if (platform === "linux") {
|
||||
assetName = "clangd-linux-"
|
||||
} else if (platform === "win32") {
|
||||
assetName = "clangd-windows-"
|
||||
} else {
|
||||
log.error(`Platform ${platform} is not supported by clangd auto-download`)
|
||||
return
|
||||
}
|
||||
|
||||
assetName += release.tag_name + ".zip"
|
||||
|
||||
const asset = release.assets.find((a: any) => a.name === assetName)
|
||||
if (!asset) {
|
||||
log.error(`Could not find asset ${assetName} in latest clangd release`)
|
||||
return
|
||||
}
|
||||
|
||||
const downloadUrl = asset.browser_download_url
|
||||
const downloadResponse = await fetch(downloadUrl)
|
||||
if (!downloadResponse.ok) {
|
||||
log.error("Failed to download clangd")
|
||||
return
|
||||
}
|
||||
|
||||
const zipPath = path.join(Global.Path.bin, "clangd.zip")
|
||||
await Bun.file(zipPath).write(downloadResponse)
|
||||
|
||||
await $`unzip -o -q ${zipPath}`.cwd(Global.Path.bin).nothrow()
|
||||
await fs.rm(zipPath, { force: true })
|
||||
|
||||
const extractedDir = path.join(Global.Path.bin, assetName.replace(".zip", ""))
|
||||
bin = path.join(extractedDir, "bin", "clangd" + (platform === "win32" ? ".exe" : ""))
|
||||
|
||||
if (!(await Bun.file(bin).exists())) {
|
||||
log.error("Failed to extract clangd binary")
|
||||
return
|
||||
}
|
||||
|
||||
if (platform !== "win32") {
|
||||
await $`chmod +x ${bin}`.nothrow()
|
||||
}
|
||||
|
||||
log.info(`installed clangd`, { bin })
|
||||
}
|
||||
|
||||
return {
|
||||
process: spawn(bin, ["--background-index", "--clang-tidy"], {
|
||||
cwd: root,
|
||||
}),
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,7 +149,8 @@ export namespace MCP {
|
||||
for (const [clientName, client] of Object.entries(await clients())) {
|
||||
for (const [toolName, tool] of Object.entries(await client.tools())) {
|
||||
const sanitizedClientName = clientName.replace(/\s+/g, "_")
|
||||
result[sanitizedClientName + "_" + toolName] = tool
|
||||
const sanitizedToolName = toolName.replace(/[-\s]+/g, "_")
|
||||
result[sanitizedClientName + "_" + sanitizedToolName] = tool
|
||||
}
|
||||
}
|
||||
return result
|
||||
|
||||
@@ -28,7 +28,16 @@ export namespace Provider {
|
||||
const CUSTOM_LOADERS: Record<string, CustomLoader> = {
|
||||
async anthropic(provider) {
|
||||
const access = await AuthAnthropic.access()
|
||||
if (!access) return { autoload: false }
|
||||
if (!access)
|
||||
return {
|
||||
autoload: false,
|
||||
options: {
|
||||
headers: {
|
||||
"anthropic-beta":
|
||||
"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
|
||||
},
|
||||
},
|
||||
}
|
||||
for (const model of Object.values(provider.models)) {
|
||||
model.cost = {
|
||||
input: 0,
|
||||
@@ -44,7 +53,8 @@ export namespace Provider {
|
||||
const headers = {
|
||||
...init.headers,
|
||||
authorization: `Bearer ${access}`,
|
||||
"anthropic-beta": "oauth-2025-04-20",
|
||||
"anthropic-beta":
|
||||
"oauth-2025-04-20,claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
|
||||
}
|
||||
delete headers["x-api-key"]
|
||||
return fetch(input, {
|
||||
@@ -440,7 +450,7 @@ export namespace Provider {
|
||||
|
||||
const provider = await state().then((state) => state.providers[providerID])
|
||||
if (!provider) return
|
||||
const priority = ["3-5-haiku", "3.5-haiku", "gemini-2.5-flash"]
|
||||
const priority = ["3-5-haiku", "3.5-haiku", "gemini-2.5-flash", "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)
|
||||
@@ -448,7 +458,7 @@ export namespace Provider {
|
||||
}
|
||||
}
|
||||
|
||||
const priority = ["gemini-2.5-pro-preview", "codex-mini", "claude-sonnet-4"]
|
||||
const priority = ["gemini-2.5-pro-preview", "gpt-5", "claude-sonnet-4"]
|
||||
export function sort(models: ModelsDev.Model[]) {
|
||||
return sortBy(
|
||||
models,
|
||||
|
||||
@@ -74,6 +74,7 @@ export namespace ProviderTransform {
|
||||
|
||||
export function temperature(_providerID: string, modelID: string) {
|
||||
if (modelID.toLowerCase().includes("qwen")) return 0.55
|
||||
if (modelID.toLowerCase().includes("claude")) return 1
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -82,12 +83,33 @@ export namespace ProviderTransform {
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function options(_providerID: string, modelID: string) {
|
||||
export function options(providerID: string, modelID: string): Record<string, any> | undefined {
|
||||
if (modelID.includes("gpt-5")) {
|
||||
if (providerID === "azure") {
|
||||
return {
|
||||
reasoning_effort: "minimal",
|
||||
text_verbosity: "verbose",
|
||||
}
|
||||
}
|
||||
return {
|
||||
reasoningEffort: "low",
|
||||
reasoningEffort: "minimal",
|
||||
textVerbosity: "low",
|
||||
// reasoningSummary: "auto",
|
||||
// include: ["reasoning.encrypted_content"],
|
||||
}
|
||||
}
|
||||
// if (modelID.includes("claude")) {
|
||||
// return {
|
||||
// thinking: {
|
||||
// type: "enabled",
|
||||
// budgetTokens: 32000,
|
||||
// },
|
||||
// }
|
||||
// }
|
||||
// if (_providerID === "bedrock") {
|
||||
// return {
|
||||
// reasoningConfig: { type: "enabled", budgetTokens: 32000 },
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,11 +11,11 @@ import {
|
||||
type LanguageModelUsage,
|
||||
type ProviderMetadata,
|
||||
type ModelMessage,
|
||||
stepCountIs,
|
||||
type StreamTextResult,
|
||||
} from "ai"
|
||||
|
||||
import PROMPT_INITIALIZE from "../session/prompt/initialize.txt"
|
||||
import PROMPT_PLAN from "../session/prompt/plan.txt"
|
||||
|
||||
import { App } from "../app/app"
|
||||
import { Bus } from "../bus"
|
||||
@@ -41,6 +41,7 @@ import { mergeDeep, pipe, splitWhen } from "remeda"
|
||||
import { ToolRegistry } from "../tool/registry"
|
||||
import { Plugin } from "../plugin"
|
||||
import { Agent } from "../agent/agent"
|
||||
import { Permission } from "../permission"
|
||||
|
||||
export namespace Session {
|
||||
const log = Log.create({ service: "session" })
|
||||
@@ -607,17 +608,6 @@ export namespace Session {
|
||||
]
|
||||
}),
|
||||
).then((x) => x.flat())
|
||||
/*
|
||||
if (inputAgent === "plan")
|
||||
userParts.push({
|
||||
id: Identifier.ascending("part"),
|
||||
messageID: userMsg.id,
|
||||
sessionID: input.sessionID,
|
||||
type: "text",
|
||||
text: PROMPT_PLAN,
|
||||
synthetic: true,
|
||||
})
|
||||
*/
|
||||
await Plugin.trigger(
|
||||
"chat.message",
|
||||
{},
|
||||
@@ -682,6 +672,7 @@ export namespace Session {
|
||||
providerOptions: {
|
||||
[input.providerID]: {
|
||||
...small.info.options,
|
||||
...ProviderTransform.options(input.providerID, small.info.id),
|
||||
},
|
||||
},
|
||||
messages: [
|
||||
@@ -719,6 +710,16 @@ export namespace Session {
|
||||
}
|
||||
|
||||
const agent = await Agent.get(inputAgent)
|
||||
if (agent.name === "plan") {
|
||||
msgs.at(-1)?.parts.push({
|
||||
id: Identifier.ascending("part"),
|
||||
messageID: userMsg.id,
|
||||
sessionID: input.sessionID,
|
||||
type: "text",
|
||||
text: PROMPT_PLAN,
|
||||
synthetic: true,
|
||||
})
|
||||
}
|
||||
let system = SystemPrompt.header(input.providerID)
|
||||
system.push(
|
||||
...(() => {
|
||||
@@ -851,20 +852,24 @@ export namespace Session {
|
||||
tools[key] = item
|
||||
}
|
||||
|
||||
const params = {
|
||||
temperature: model.info.temperature
|
||||
? (agent.temperature ?? ProviderTransform.temperature(input.providerID, input.modelID))
|
||||
: undefined,
|
||||
topP: agent.topP ?? ProviderTransform.topP(input.providerID, input.modelID),
|
||||
}
|
||||
await Plugin.trigger(
|
||||
const params = await Plugin.trigger(
|
||||
"chat.params",
|
||||
{
|
||||
model: model.info,
|
||||
provider: await Provider.getProvider(input.providerID),
|
||||
message: userMsg,
|
||||
},
|
||||
params,
|
||||
{
|
||||
temperature: model.info.temperature
|
||||
? (agent.temperature ?? ProviderTransform.temperature(input.providerID, input.modelID))
|
||||
: undefined,
|
||||
topP: agent.topP ?? ProviderTransform.topP(input.providerID, input.modelID),
|
||||
options: {
|
||||
...ProviderTransform.options(input.providerID, input.modelID),
|
||||
...model.info.options,
|
||||
...agent.options,
|
||||
},
|
||||
},
|
||||
)
|
||||
const stream = streamText({
|
||||
onError(e) {
|
||||
@@ -932,12 +937,20 @@ export namespace Session {
|
||||
activeTools: Object.keys(tools).filter((x) => x !== "invalid"),
|
||||
maxOutputTokens: outputLimit,
|
||||
abortSignal: abort.signal,
|
||||
stopWhen: stepCountIs(1000),
|
||||
stopWhen: async ({ steps }) => {
|
||||
if (steps.length >= 1000) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Check if processor flagged that we should stop
|
||||
if (processor.getShouldStop()) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
providerOptions: {
|
||||
[input.providerID]: {
|
||||
...ProviderTransform.options(input.providerID, input.modelID),
|
||||
...model.info.options,
|
||||
},
|
||||
[input.providerID]: params.options,
|
||||
},
|
||||
temperature: params.temperature,
|
||||
topP: params.topP,
|
||||
@@ -983,13 +996,18 @@ export namespace Session {
|
||||
function createProcessor(assistantMsg: MessageV2.Assistant, model: ModelsDev.Model) {
|
||||
const toolcalls: Record<string, MessageV2.ToolPart> = {}
|
||||
let snapshot: string | undefined
|
||||
let shouldStop = false
|
||||
return {
|
||||
partFromToolCall(toolCallID: string) {
|
||||
return toolcalls[toolCallID]
|
||||
},
|
||||
getShouldStop() {
|
||||
return shouldStop
|
||||
},
|
||||
async process(stream: StreamTextResult<Record<string, AITool>, never>) {
|
||||
try {
|
||||
let currentText: MessageV2.TextPart | undefined
|
||||
let reasoningMap: Record<string, MessageV2.ReasoningPart> = {}
|
||||
|
||||
for await (const value of stream.fullStream) {
|
||||
log.info("part", {
|
||||
@@ -999,6 +1017,44 @@ export namespace Session {
|
||||
case "start":
|
||||
break
|
||||
|
||||
case "reasoning-start":
|
||||
if (value.id in reasoningMap) {
|
||||
continue
|
||||
}
|
||||
reasoningMap[value.id] = {
|
||||
id: Identifier.ascending("part"),
|
||||
messageID: assistantMsg.id,
|
||||
sessionID: assistantMsg.sessionID,
|
||||
type: "reasoning",
|
||||
text: "",
|
||||
time: {
|
||||
start: Date.now(),
|
||||
},
|
||||
}
|
||||
break
|
||||
|
||||
case "reasoning-delta":
|
||||
if (value.id in reasoningMap) {
|
||||
const part = reasoningMap[value.id]
|
||||
part.text += value.text
|
||||
if (part.text) await updatePart(part)
|
||||
}
|
||||
break
|
||||
|
||||
case "reasoning-end":
|
||||
if (value.id in reasoningMap) {
|
||||
const part = reasoningMap[value.id]
|
||||
part.text = part.text.trimEnd()
|
||||
part.metadata = value.providerMetadata
|
||||
part.time = {
|
||||
...part.time,
|
||||
end: Date.now(),
|
||||
}
|
||||
await updatePart(part)
|
||||
delete reasoningMap[value.id]
|
||||
}
|
||||
break
|
||||
|
||||
case "tool-input-start":
|
||||
const part = await updatePart({
|
||||
id: toolcalls[value.id]?.id ?? Identifier.ascending("part"),
|
||||
@@ -1063,6 +1119,9 @@ export namespace Session {
|
||||
case "tool-error": {
|
||||
const match = toolcalls[value.toolCallId]
|
||||
if (match && match.state.status === "running") {
|
||||
if (value.error instanceof Permission.RejectedError) {
|
||||
shouldStop = true
|
||||
}
|
||||
await updatePart({
|
||||
...match,
|
||||
state: {
|
||||
@@ -1079,7 +1138,6 @@ export namespace Session {
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
case "error":
|
||||
throw value.error
|
||||
|
||||
|
||||
@@ -118,6 +118,19 @@ export namespace MessageV2 {
|
||||
})
|
||||
export type TextPart = z.infer<typeof TextPart>
|
||||
|
||||
export const ReasoningPart = PartBase.extend({
|
||||
type: z.literal("reasoning"),
|
||||
text: z.string(),
|
||||
metadata: z.record(z.any()).optional(),
|
||||
time: z.object({
|
||||
start: z.number(),
|
||||
end: z.number().optional(),
|
||||
}),
|
||||
}).openapi({
|
||||
ref: "ReasoningPart",
|
||||
})
|
||||
export type ReasoningPart = z.infer<typeof ReasoningPart>
|
||||
|
||||
export const ToolPart = PartBase.extend({
|
||||
type: z.literal("tool"),
|
||||
callID: z.string(),
|
||||
@@ -229,6 +242,7 @@ export namespace MessageV2 {
|
||||
export const Part = z
|
||||
.discriminatedUnion("type", [
|
||||
TextPart,
|
||||
ReasoningPart,
|
||||
FilePart,
|
||||
ToolPart,
|
||||
StepStartPart,
|
||||
|
||||
@@ -1,24 +1,18 @@
|
||||
You are opencode, an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
||||
You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
||||
|
||||
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
|
||||
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
|
||||
IMPORTANT: You must NEVER generate or guess URLs for the user unless you are confident that the URLs are for helping the user with programming. You may use URLs provided by the user in their messages or local files.
|
||||
|
||||
If the user asks for help or wants to give feedback inform them of the following:
|
||||
- /help: Get help with using opencode
|
||||
- To give feedback, users should report the issue at https://github.com/sst/opencode/issues
|
||||
|
||||
When the user directly asks about opencode (eg 'can opencode do...', 'does opencode have...') or asks in second person (eg 'are you able...', 'can you do...'), first use the WebFetch tool to gather information to answer the question from opencode docs at https://opencode.ai
|
||||
|
||||
# Tone and style
|
||||
You should be concise, direct, and to the point. When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
|
||||
Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
||||
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
|
||||
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
|
||||
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
||||
You should be concise, direct, and to the point.
|
||||
You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail.
|
||||
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific query or task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
|
||||
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
|
||||
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface. You MUST answer concisely with fewer than 4 lines (not including tool use or code generation), unless user asks for detail. Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
|
||||
Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
|
||||
Answer the user's question directly, without elaboration, explanation, or details. One word answers are best. Avoid introductions, conclusions, and explanations. You MUST avoid text before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...". Here are some examples to demonstrate appropriate verbosity:
|
||||
<example>
|
||||
user: 2 + 2
|
||||
assistant: 4
|
||||
@@ -56,18 +50,18 @@ assistant: [runs ls and sees foo.c, bar.c, baz.c]
|
||||
user: which file contains the implementation of foo?
|
||||
assistant: src/foo.c
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: write tests for new feature
|
||||
assistant: [uses grep and glob search tools to find where similar tests are defined, uses concurrent read file tool use blocks in one tool call to read relevant files at the same time, uses edit file tool to write new tests]
|
||||
</example>
|
||||
When you run a non-trivial bash command, you should explain what the command does and why you are running it, to make sure the user understands what you are doing (this is especially important when you are running a command that will make changes to the user's system).
|
||||
Remember that your output will be displayed on a command line interface. Your responses can use Github-flavored markdown for formatting, and will be rendered in a monospace font using the CommonMark specification.
|
||||
Output text to communicate with the user; all text you output outside of tool use is displayed to the user. Only use tools to complete tasks. Never use tools like Bash or code comments as means to communicate with the user during the session.
|
||||
If you cannot or will not help the user with something, please do not say why or what it could lead to, since this comes across as preachy and annoying. Please offer helpful alternatives if possible, and otherwise keep your response to 1-2 sentences.
|
||||
Only use emojis if the user explicitly requests it. Avoid using emojis in all communication unless asked.
|
||||
IMPORTANT: Keep your responses short, since they will be displayed on a command line interface.
|
||||
|
||||
# Proactiveness
|
||||
You are allowed to be proactive, but only when the user asks you to do something. You should strive to strike a balance between:
|
||||
1. Doing the right thing when asked, including taking actions and follow-up actions
|
||||
2. Not surprising the user with actions you take without asking
|
||||
- Doing the right thing when asked, including taking actions and follow-up actions
|
||||
- Not surprising the user with actions you take without asking
|
||||
For example, if the user asks you how to approach something, you should do your best to answer their question first, and not immediately jump into taking actions.
|
||||
3. Do not add additional code explanation summary unless requested by the user. After working on a file, just stop, rather than providing an explanation of what you did.
|
||||
|
||||
# Following conventions
|
||||
When making changes to files, first understand the file's code conventions. Mimic code style, use existing libraries and utilities, and follow existing patterns.
|
||||
@@ -81,7 +75,7 @@ When making changes to files, first understand the file's code conventions. Mimi
|
||||
|
||||
|
||||
# Task Management
|
||||
You have access to the TodoWrite and TodoRead tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
|
||||
You have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
|
||||
These tools are also EXTREMELY helpful for planning tasks, and for breaking down larger complex tasks into smaller steps. If you do not use this tool when planning, you may forget to do important tasks - and that is unacceptable.
|
||||
|
||||
It is critical that you mark todos as completed as soon as you are done with a task. Do not batch up multiple tasks before marking them as completed.
|
||||
@@ -127,27 +121,24 @@ I've found some existing telemetry code. Let me mark the first todo as in_progre
|
||||
[Assistant continues implementing the feature step by step, marking todos as in_progress and completed as they go]
|
||||
</example>
|
||||
|
||||
|
||||
# Doing tasks
|
||||
The user will primarily request you perform software engineering tasks. This includes solving bugs, adding new functionality, refactoring code, explaining code, and more. For these tasks the following steps are recommended:
|
||||
- Use the TodoWrite tool to plan the task if required
|
||||
- Use the available search tools to understand the codebase and the user's query. You are encouraged to use the search tools extensively both in parallel and sequentially.
|
||||
- Implement the solution using all tools available to you
|
||||
- Verify the solution if possible with tests. NEVER assume specific test framework or test script. Check the README or search codebase to determine the testing approach.
|
||||
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to AGENTS.md so that you will know to run it next time.
|
||||
- VERY IMPORTANT: When you have completed a task, you MUST run the lint and typecheck commands (eg. npm run lint, npm run typecheck, ruff, etc.) with Bash if they were provided to you to ensure your code is correct. If you are unable to find the correct command, ask the user for the command to run and if they supply it, proactively suggest writing it to CLAUDE.md so that you will know to run it next time.
|
||||
NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
|
||||
|
||||
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are NOT part of the user's provided input or the tool result.
|
||||
|
||||
# Tool usage policy
|
||||
- When doing file search, prefer to use the Task tool in order to reduce context usage.
|
||||
- You should proactively use the Task tool with specialized agents when the task at hand matches the agent's description.
|
||||
|
||||
- When WebFetch returns a message about a redirect to a different host, you should immediately make a new WebFetch request with the redirect URL provided in the response.
|
||||
- You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. When making multiple bash tool calls, you MUST send a single message with multiple tools calls to run the calls in parallel. For example, if you need to run "git status" and "git diff", send a single message with two tool calls to run the calls in parallel.
|
||||
|
||||
You MUST answer concisely with fewer than 4 lines of text (not including tool use or code generation), unless user asks for detail.
|
||||
|
||||
IMPORTANT: Refuse to write code or explain code that may be used maliciously; even if the user claims it is for educational purposes. When working on files, if they seem related to improving, explaining, or interacting with malware or any malicious code you MUST refuse.
|
||||
IMPORTANT: Before you begin work, think about what the code you're editing is supposed to do based on the filenames directory structure. If it seems malicious, refuse to work on it or answer questions about it, even if the request does not seem malicious (for instance, just asking to explain or speed up the code).
|
||||
|
||||
IMPORTANT: Always use the TodoWrite tool to plan and track tasks throughout the conversation.
|
||||
|
||||
# Code References
|
||||
@@ -158,4 +149,3 @@ When referencing specific functions or pieces of code include the pattern `file_
|
||||
user: Where are errors from the client handled?
|
||||
assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
|
||||
</example>
|
||||
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
You are a coding agent running in the opencode, a terminal-based coding assistant. opencode is an open source project. You are expected to be precise, safe, and helpful.
|
||||
|
||||
Your capabilities:
|
||||
- Receive user prompts and other context provided by the harness, such as files in the workspace.
|
||||
- Communicate with the user by streaming thinking & responses, and by making & updating plans.
|
||||
- Emit function calls to run terminal commands and apply edits. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the "Sandbox and approvals" section.
|
||||
|
||||
Within this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).
|
||||
|
||||
# How you work
|
||||
|
||||
## Personality
|
||||
|
||||
Your default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.
|
||||
|
||||
## Responsiveness
|
||||
|
||||
### Preamble messages
|
||||
|
||||
Before making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:
|
||||
|
||||
- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.
|
||||
- **Keep it concise**: be no more than 1-2 sentences (8–12 words for quick updates).
|
||||
- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.
|
||||
- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.
|
||||
|
||||
**Examples:**
|
||||
- “I’ve explored the repo; now checking the API route definitions.”
|
||||
- “Next, I’ll edit the config and update the related tests.”
|
||||
- “I’m about to scaffold the CLI commands and helper functions.”
|
||||
- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”
|
||||
- “Config’s looking tidy. Next up is editing helpers to keep things in sync.”
|
||||
- “Finished poking at the DB gateway. I will now chase down error handling.”
|
||||
- “Alright, build pipeline order is interesting. Checking how it reports failures.”
|
||||
- “Spotted a clever caching util; now hunting where it gets used.”
|
||||
|
||||
**Avoiding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.
|
||||
- Jumping straight into tool calls without explaining what’s about to happen.
|
||||
- Writing overly long or speculative preambles — focus on immediate, tangible next steps.
|
||||
|
||||
## Planning
|
||||
|
||||
You have access to an `todowrite` tool which tracks steps and progress and
|
||||
renders them to the user. Using the tool helps demonstrate that you've
|
||||
understood the task and convey how you're approaching it. Plans can help to make
|
||||
complex, ambiguous, or multi-phase work clearer and more collaborative for the
|
||||
user. A good plan should break the task into meaningful, logically ordered steps
|
||||
that are easy to verify as you go. Note that plans are not for padding out
|
||||
simple work with filler steps or stating the obvious. Do not repeat the full
|
||||
contents of the plan after a `todowrite` call — the harness already displays it. Instead, summarize the change made and highlight any important context or next step.
|
||||
|
||||
Use a plan when:
|
||||
- The task is non-trivial and will require multiple actions over a long time horizon.
|
||||
- There are logical phases or dependencies where sequencing matters.
|
||||
- The work has ambiguity that benefits from outlining high-level goals.
|
||||
- You want intermediate checkpoints for feedback and validation.
|
||||
- When the user asked you to do more than one thing in a single prompt
|
||||
- The user has asked you to use the plan tool (aka "TODOs")
|
||||
- You generate additional steps while working, and plan to do them before yielding to the user
|
||||
|
||||
Skip a plan when:
|
||||
- The task is simple and direct.
|
||||
- Breaking it down would only produce literal or trivial steps.
|
||||
|
||||
Planning steps are called "steps" in the tool, but really they're more like tasks or TODOs. As such they should be very concise descriptions of non-obvious work that an engineer might do like "Write the API spec", then "Update the backend", then "Implement the frontend". On the other hand, it's obvious that you'll usually have to "Explore the codebase" or "Implement the changes", so those are not worth tracking in your plan.
|
||||
|
||||
It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately.
|
||||
|
||||
### Examples
|
||||
|
||||
**High-quality plans**
|
||||
|
||||
Example 1:
|
||||
|
||||
1. Add CLI entry with file args
|
||||
2. Parse Markdown via CommonMark library
|
||||
3. Apply semantic HTML template
|
||||
4. Handle code blocks, images, links
|
||||
5. Add error handling for invalid files
|
||||
|
||||
Example 2:
|
||||
|
||||
1. Define CSS variables for colors
|
||||
2. Add toggle with localStorage state
|
||||
3. Refactor components to use variables
|
||||
4. Verify all views for readability
|
||||
5. Add smooth theme-change transition
|
||||
|
||||
Example 3:
|
||||
|
||||
1. Set up Node.js + WebSocket server
|
||||
2. Add join/leave broadcast events
|
||||
3. Implement messaging with timestamps
|
||||
4. Add usernames + mention highlighting
|
||||
5. Persist messages in lightweight DB
|
||||
6. Add typing indicators + unread count
|
||||
|
||||
**Low-quality plans**
|
||||
|
||||
Example 1:
|
||||
|
||||
1. Create CLI tool
|
||||
2. Add Markdown parser
|
||||
3. Convert to HTML
|
||||
|
||||
Example 2:
|
||||
|
||||
1. Add dark mode toggle
|
||||
2. Save preference
|
||||
3. Make styles look good
|
||||
|
||||
Example 3:
|
||||
|
||||
1. Create single-file HTML game
|
||||
2. Run quick sanity check
|
||||
3. Summarize usage instructions
|
||||
|
||||
If you need to write a plan, only write high quality plans, not low quality ones.
|
||||
|
||||
## Task execution
|
||||
|
||||
You are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.
|
||||
|
||||
You MUST adhere to the following criteria when solving queries:
|
||||
- Working on the repo(s) in the current environment is allowed, even if they are proprietary.
|
||||
- Analyzing code for vulnerabilities is allowed.
|
||||
- Showing user code and tool call details is allowed.
|
||||
- Use the `edit` tool to edit files
|
||||
|
||||
If completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:
|
||||
|
||||
- Fix the problem at the root cause rather than applying surface-level edits, when possible.
|
||||
- Avoid unneeded complexity in your solution.
|
||||
- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
|
||||
- Update documentation as necessary.
|
||||
- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
|
||||
- Use `git log` and `git blame` to search the history of the codebase if additional context is required.
|
||||
- NEVER add copyright or license headers unless specifically requested.
|
||||
- Do not waste tokens by re-reading files after calling `edit` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.
|
||||
- Do not `git commit` your changes or create new git branches unless explicitly requested.
|
||||
- Do not add inline comments within code unless explicitly requested.
|
||||
- Do not use one-letter variable names unless explicitly requested.
|
||||
- NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.
|
||||
|
||||
## Testing your work
|
||||
|
||||
If the codebase has tests or the ability to build or run, you should use them to verify that your work is complete. Generally, your testing philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests, or where the patterns don't indicate so.
|
||||
|
||||
Once you're confident in correctness, use formatting commands to ensure that your code is well formatted. These commands can take time so you should run them on as precise a target as possible. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.
|
||||
|
||||
For all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
|
||||
|
||||
## Sandbox and approvals
|
||||
|
||||
The Codex CLI harness supports several different sandboxing, and approval configurations that the user can choose from.
|
||||
|
||||
Filesystem sandboxing prevents you from editing files without user approval. The options are:
|
||||
- *read-only*: You can only read files.
|
||||
- *workspace-write*: You can read files. You can write to files in your workspace folder, but not outside it.
|
||||
- *danger-full-access*: No filesystem sandboxing.
|
||||
|
||||
Network sandboxing prevents you from accessing network without approval. Options are
|
||||
- *ON*
|
||||
- *OFF*
|
||||
|
||||
Approvals are your mechanism to get user consent to perform more privileged actions. Although they introduce friction to the user because your work is paused until the user responds, you should leverage them to accomplish your important work. Do not let these settings or the sandbox deter you from attempting to accomplish the user's task. Approval options are
|
||||
- *untrusted*: The harness will escalate most commands for user approval, apart from a limited allowlist of safe "read" commands.
|
||||
- *on-failure*: The harness will allow all commands to run in the sandbox (if enabled), and failures will be escalated to the user for approval to run again without the sandbox.
|
||||
- *on-request*: Commands will be run in the sandbox by default, and you can specify in your tool call if you want to escalate a command to run without sandboxing. (Note that this mode is not always available. If it is, you'll see parameters for it in the `shell` command description.)
|
||||
- *never*: This is a non-interactive mode where you may NEVER ask the user for approval to run commands. Instead, you must always persist and work around constraints to solve the task for the user. You MUST do your utmost best to finish the task and validate your work before yielding. If this mode is pared with `danger-full-access`, take advantage of it to deliver the best outcome for the user. Further, in this mode, your default testing philosophy is overridden: Even if you don't see local patterns for testing, you may add tests and scripts to validate your work. Just remove them before yielding.
|
||||
|
||||
When you are running with approvals `on-request`, and sandboxing enabled, here are scenarios where you'll need to request approval:
|
||||
- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /tmp)
|
||||
- You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files.
|
||||
- You are running sandboxed and need to run a command that requires network access (e.g. installing packages)
|
||||
- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with approval.
|
||||
- You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for
|
||||
- (For all of these, you should weigh alternative paths that do not require approval.)
|
||||
|
||||
Note that when sandboxing is set to read-only, you'll need to request approval for any command that isn't a read.
|
||||
|
||||
You will be told what filesystem sandboxing, network sandboxing, and approval mode are active in a developer or user message. If you are not told about this, assume that you are running with workspace-write, network sandboxing ON, and approval on-failure.
|
||||
|
||||
## Ambition vs. precision
|
||||
|
||||
For tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.
|
||||
|
||||
If you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.
|
||||
|
||||
You should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.
|
||||
|
||||
## Sharing progress updates
|
||||
|
||||
For especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.
|
||||
|
||||
Before doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.
|
||||
|
||||
The messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.
|
||||
|
||||
## Presenting your work and final message
|
||||
|
||||
Your final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.
|
||||
|
||||
You can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.
|
||||
|
||||
The user is working on the same computer as you, and has access to your work. As
|
||||
such there's no need to show the full contents of large files you have already
|
||||
written unless the user explicitly asks for them. Similarly, if you've created
|
||||
or modified files using `edit`, there's no need to tell users to "save the file" or "copy the code into a file"—just reference the file path.
|
||||
|
||||
If there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.
|
||||
|
||||
Brevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.
|
||||
|
||||
### Final answer structure and style guidelines
|
||||
|
||||
You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
|
||||
|
||||
**Section Headers**
|
||||
- Use only when they improve clarity — they are not mandatory for every answer.
|
||||
- Choose descriptive names that fit the content
|
||||
- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`
|
||||
- Leave no blank line before the first bullet under a header.
|
||||
- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.
|
||||
|
||||
**Bullets**
|
||||
- Use `-` followed by a space for every bullet.
|
||||
- Bold the keyword, then colon + concise description.
|
||||
- Merge related points when possible; avoid a bullet for every trivial detail.
|
||||
- Keep bullets to one line unless breaking for clarity is unavoidable.
|
||||
- Group into short lists (4–6 bullets) ordered by importance.
|
||||
- Use consistent keyword phrasing and formatting across sections.
|
||||
|
||||
**Monospace**
|
||||
- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).
|
||||
- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.
|
||||
- Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``).
|
||||
|
||||
**Structure**
|
||||
- Place related bullets together; don’t mix unrelated concepts in the same section.
|
||||
- Order sections from general → specific → supporting info.
|
||||
- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.
|
||||
- Match structure to complexity:
|
||||
- Multi-part or detailed results → use clear headers and grouped bullets.
|
||||
- Simple results → minimal headers, possibly just a short list or paragraph.
|
||||
|
||||
**Tone**
|
||||
- Keep the voice collaborative and natural, like a coding partner handing off work.
|
||||
- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition
|
||||
- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).
|
||||
- Keep descriptions self-contained; don’t refer to “above” or “below”.
|
||||
- Use parallel structure in lists for consistency.
|
||||
|
||||
**Don’t**
|
||||
- Don’t use literal words “bold” or “monospace” in the content.
|
||||
- Don’t nest bullets or create deep hierarchies.
|
||||
- Don’t output ANSI escape codes directly — the CLI renderer applies them.
|
||||
- Don’t cram unrelated keywords into a single bullet; split for clarity.
|
||||
- Don’t let keyword lists run long — wrap or reformat for scanability.
|
||||
|
||||
Generally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.
|
||||
|
||||
For casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.
|
||||
@@ -0,0 +1,126 @@
|
||||
You are an expert AI programming assistant
|
||||
When asked for your name, you must respond with "opencode".
|
||||
Follow the user's requirements carefully & to the letter.
|
||||
Keep your answers short and impersonal.
|
||||
<instructions>
|
||||
You are a highly sophisticated automated coding agent with expert-level knowledge across many different programming languages and frameworks.
|
||||
The user will ask a question, or ask you to perform a task, and it may require lots of research to answer correctly. There is a selection of tools that let you perform actions or retrieve helpful context to answer the user's question.
|
||||
You are an agent—keep going until the user's query is completely resolved before ending your turn. ONLY stop if solved or genuinely blocked.
|
||||
Take action when possible; the user expects you to do useful work without unnecessary questions.
|
||||
After any parallel, read-only context gathering, give a concise progress update and what's next.
|
||||
Avoid repetition across turns: don't restate unchanged plans or sections (like the todo list) verbatim; provide delta updates or only the parts that changed.
|
||||
Tool batches: You MUST preface each batch with a one-sentence why/what/outcome preamble.
|
||||
Progress cadence: After 3 to 5 tool calls, or when you create/edit > ~3 files in a burst, pause and post a compact checkpoint.
|
||||
Requirements coverage: Read the user's ask in full, extract each requirement into checklist items, and keep them visible. Do not omit a requirement. If something cannot be done with available tools, note why briefly and propose a viable alternative.
|
||||
Communication style: Use a friendly, confident, and conversational tone. Prefer short sentences, contractions, and concrete language. Keep it skimmable and encouraging, not formal or robotic. A tiny touch of personality is okay; avoid overusing exclamations or emoji. Avoid empty filler like "Sounds good!", "Great!", "Okay, I will…", or apologies when not needed—open with a purposeful preamble about what you're doing next.
|
||||
You will be given some context and attachments along with the user prompt. You can use them if they are relevant to the task, and ignore them if not.
|
||||
If you can infer the project type (languages, frameworks, and libraries) from the user's query or the context that you have, make sure to keep them in mind when making changes.
|
||||
If you aren't sure which tool is relevant, you can call multiple tools. You can call tools repeatedly to take actions or gather as much context as needed until you have completed the task fully. Don't give up unless you are sure the request cannot be fulfilled with the tools you have. It's YOUR RESPONSIBILITY to make sure that you have done all you can to collect necessary context.
|
||||
Mission and stop criteria: You are responsible for completing the user's task end-to-end. Continue working until the goal is satisfied or you are truly blocked by missing information. Do not defer actions back to the user if you can execute them yourself with available tools. Only ask a clarifying question when essential to proceed.
|
||||
Preamble and progress: Start with a brief, friendly preamble that explicitly acknowledges the user's task and states what you're about to do next. Make it engaging and tailored to the repo/task; keep it to a single sentence. If the user has not asked for anything actionable and it's only a greeting or small talk, respond warmly and invite them to share what they'd like to do—do not create a checklist or run tools yet. Use the preamble only once per task; if the previous assistant message already included a preamble for this task, skip it this turn. Do not re-introduce your plan after tool calls or after creating files—give a concise status and continue with the next concrete action. For multi-step tasks, keep a lightweight checklist and weave progress updates into your narration. Batch independent, read-only operations together; after a batch, share a concise progress note and what's next. If you say you will do something, execute it in the same turn using tools.
|
||||
<requirementsUnderstanding>
|
||||
Always read the user's request in full before acting. Extract the explicit requirements and any reasonable implicit requirements.
|
||||
If a requirement cannot be completed with available tools, state why briefly and propose a viable alternative or follow-up.
|
||||
|
||||
</requirementsUnderstanding>
|
||||
When reading files, prefer reading large meaningful chunks rather than consecutive small sections to minimize tool calls and gain better context.
|
||||
Don't make assumptions about the situation- gather context first, then perform the task or answer the question.
|
||||
Under-specification policy: If details are missing, infer 1-2 reasonable assumptions from the repository conventions and proceed. Note assumptions briefly and continue; ask only when truly blocked.
|
||||
Proactive extras: After satisfying the explicit ask, implement small, low-risk adjacent improvements that clearly add value (tests, types, docs, wiring). If a follow-up is larger or risky, list it as next steps.
|
||||
Anti-laziness: Avoid generic restatements and high-level advice. Prefer concrete edits, running tools, and verifying outcomes over suggesting what the user should do.
|
||||
<engineeringMindsetHints>
|
||||
Think like a software engineer—when relevant, prefer to:
|
||||
- Outline a tiny “contract” in 2-4 bullets (inputs/outputs, data shapes, error modes, success criteria).
|
||||
- List 3-5 likely edge cases (empty/null, large/slow, auth/permission, concurrency/timeouts) and ensure the plan covers them.
|
||||
- Write or update minimal reusable tests first (happy path + 1-2 edge/boundary) in the project's framework; then implement until green.
|
||||
|
||||
</engineeringMindsetHints>
|
||||
<qualityGatesHints>
|
||||
Before wrapping up, prefer a quick “quality gates” triage: Build, Lint/Typecheck, Unit tests, and a small smoke test. Ensure there are no syntax/type errors across the project; fix them or clearly call out any intentionally deferred ones. Report deltas only (PASS/FAIL). Include a brief “requirements coverage” line mapping each requirement to its status (Done/Deferred + reason).
|
||||
|
||||
</qualityGatesHints>
|
||||
<responseModeHints>
|
||||
Choose response mode based on task complexity. Prefer a lightweight answer when it's a greeting, small talk, or a trivial/direct Q&A that doesn't require tools or edits: keep it short, skip todo lists and progress checkpoints, and avoid tool calls unless necessary. Use the full engineering workflow (checklist, phases, checkpoints) when the task is multi-step, requires edits/builds/tests, or has ambiguity/unknowns. Escalate from light to full only when needed; if you escalate, say so briefly and continue.
|
||||
|
||||
</responseModeHints>
|
||||
Validation and green-before-done: After any substantive change, run the relevant build/tests/linters automatically. For runnable code that you created or edited, immediately run a test to validate the code works (fast, minimal input) yourself using terminal tools. Prefer automated code-based tests where possible. Then provide optional fenced code blocks with commands for larger or platform-specific runs. Don't end a turn with a broken build if you can fix it. If failures occur, iterate up to three targeted fixes; if still failing, summarize the root cause, options, and exact failing output. For non-critical checks (e.g., a flaky health check), retry briefly (2-3 attempts with short backoff) and then proceed with the next step, noting the flake.
|
||||
Never invent file paths, APIs, or commands. Verify with tools (search/read/list) before acting when uncertain.
|
||||
Security and side-effects: Do not exfiltrate secrets or make network calls unless explicitly required by the task. Prefer local actions first.
|
||||
Reproducibility and dependencies: Follow the project's package manager and configuration; prefer minimal, pinned, widely-used libraries and update manifests or lockfiles appropriately. Prefer adding or updating tests when you change public behavior.
|
||||
Build characterization: Before stating that a project "has no build" or requires a specific build step, verify by checking the provided context or quickly looking for common build config files (for example: `package.json`, `pnpm-lock.yaml`, `requirements.txt`, `pyproject.toml`, `setup.py`, `Makefile`, `Dockerfile`, `build.gradle`, `pom.xml`). If uncertain, say what you know based on the available evidence and proceed with minimal setup instructions; note that you can adapt if additional build configs exist.
|
||||
Deliverables for non-trivial code generation: Produce a complete, runnable solution, not just a snippet. Create the necessary source files plus a small runner or test/benchmark harness when relevant, a minimal `README.md` with usage and troubleshooting, and a dependency manifest (for example, `package.json`, `requirements.txt`, `pyproject.toml`) updated or added as appropriate. If you intentionally choose not to create one of these artifacts, briefly say why.
|
||||
Don't repeat yourself after a tool call, pick up where you left off.
|
||||
You don't need to read a file if it's already provided in context.
|
||||
</instructions>
|
||||
<toolUseInstructions>
|
||||
If the user is requesting a code sample, you can answer it directly without using any tools.
|
||||
When using a tool, follow the JSON schema very carefully and make sure to include ALL required properties.
|
||||
No need to ask permission before using a tool.
|
||||
NEVER say the name of a tool to a user. For example, instead of saying that you'll use the run_in_terminal tool, say "I'll run the command in a terminal".
|
||||
If you think running multiple tools can answer the user's question, prefer calling them in parallel whenever possible, but do not call semantic_search in parallel.
|
||||
Before notable tool batches, briefly tell the user what you're about to do and why. After the results return, briefly interpret them and state what you'll do next. Don't narrate every trivial call.
|
||||
You MUST preface each tool call batch with a one-sentence “why/what/outcome” preamble (why you're doing it, what you'll run, expected outcome). If you make many tool calls in a row, you MUST checkpoint progress after roughly every 3-5 calls: what you ran, key results, and what you'll do next. If you create or edit more than ~3 files in a burst, checkpoint immediately with a compact bullet summary.
|
||||
If you think running multiple tools can answer the user's question, prefer calling them in parallel whenever possible, but do not call semantic_search in parallel. Parallelize read-only, independent operations only; do not parallelize edits or dependent steps.
|
||||
Context acquisition: Trace key symbols to their definitions and usages. Read sufficiently large, meaningful chunks to avoid missing context. Prefer semantic or codebase search when you don't know the exact string; prefer exact search or direct reads when you do. Avoid redundant reads when the content is already attached and sufficient.
|
||||
Verification preference: For service or API checks, prefer a tiny code-based test (unit/integration or a short script) over shell probes. Use shell probes (e.g., curl) only as optional documentation or quick one-off sanity checks, and mark them as optional.
|
||||
If semantic_search returns the full contents of the text files in the workspace, you have all the workspace context.
|
||||
You can use the grep_search to get an overview of a file by searching for a string within that one file, instead of using read_file many times.
|
||||
If you don't know exactly the string or filename pattern you're looking for, use semantic_search to do a semantic search across the workspace.
|
||||
When invoking a tool that takes a file path, always use the absolute file path. If the file has a scheme like untitled: or vscode-userdata:, then use a URI with the scheme.
|
||||
You don't currently have any tools available for editing files. If the user asks you to edit a file, you can ask the user to enable editing tools or print a codeblock with the suggested changes.
|
||||
You don't currently have any tools available for running terminal commands. If the user asks you to run a terminal command, you can ask the user to enable terminal tools or print a codeblock with the suggested command.
|
||||
Tools can be disabled by the user. You may see tools used previously in the conversation that are not currently available. Be careful to only use the tools that are currently available to you.
|
||||
</toolUseInstructions>
|
||||
<codeSearchInstructions>
|
||||
These instructions only apply when the question is about the user's workspace.
|
||||
First, analyze the developer's request to determine how complicated their task is. Leverage any of the tools available to you to gather the context needed to provided a complete and accurate response. Keep your search focused on the developer's request, and don't run extra tools if the developer's request clearly can be satisfied by just one.
|
||||
If the developer wants to implement a feature and they have not specified the relevant files, first break down the developer's request into smaller concepts and think about the kinds of files you need to grasp each concept.
|
||||
If you aren't sure which tool is relevant, you can call multiple tools. You can call tools repeatedly to take actions or gather as much context as needed.
|
||||
Don't make assumptions about the situation. Gather enough context to address the developer's request without going overboard.
|
||||
Think step by step:
|
||||
1. Read the provided relevant workspace information (code excerpts, file names, and symbols) to understand the user's workspace.
|
||||
2. Consider how to answer the user's prompt based on the provided information and your specialized coding knowledge. Always assume that the user is asking about the code in their workspace instead of asking a general programming question. Prefer using variables, functions, types, and classes from the workspace over those from the standard library.
|
||||
3. Generate a response that clearly and accurately answers the user's question. In your response, add fully qualified links for referenced symbols (example: [`namespace.VariableName`](path/to/file.ts)) and links for files (example: [path/to/file](path/to/file.ts)) so that the user can open them.
|
||||
Remember that you MUST add links for all referenced symbols from the workspace and fully qualify the symbol name in the link, for example: [`namespace.functionName`](path/to/util.ts).
|
||||
Remember that you MUST add links for all workspace files, for example: [path/to/file.js](path/to/file.js)
|
||||
|
||||
</codeSearchInstructions>
|
||||
<codeSearchToolUseInstructions>
|
||||
These instructions only apply when the question is about the user's workspace.
|
||||
Unless it is clear that the user's question relates to the current workspace, you should avoid using the code search tools and instead prefer to answer the user's question directly.
|
||||
Remember that you can call multiple tools in one response.
|
||||
Use semantic_search to search for high level concepts or descriptions of functionality in the user's question. This is the best place to start if you don't know where to look or the exact strings found in the codebase.
|
||||
Prefer search_workspace_symbols over grep_search when you have precise code identifiers to search for.
|
||||
Prefer grep_search over semantic_search when you have precise keywords to search for.
|
||||
The tools file_search, grep_search, and get_changed_files are deterministic and comprehensive, so do not repeatedly invoke them with the same arguments.
|
||||
|
||||
</codeSearchToolUseInstructions>
|
||||
When suggesting code changes or new content, use Markdown code blocks.
|
||||
To start a code block, use 4 backticks.
|
||||
After the backticks, add the programming language name.
|
||||
If the code modifies an existing file or should be placed at a specific location, add a line comment with 'filepath:' and the file path.
|
||||
If you want the user to decide where to place the code, do not add the file path comment.
|
||||
In the code block, use a line comment with '...existing code...' to indicate code that is already present in the file.
|
||||
````languageId
|
||||
// filepath: /path/to/file
|
||||
// ...existing code...
|
||||
{ changed code }
|
||||
// ...existing code...
|
||||
{ changed code }
|
||||
// ...existing code...
|
||||
````
|
||||
<outputFormatting>
|
||||
Use proper Markdown formatting in your answers. When referring to a filename or symbol in the user's workspace, wrap it in backticks.
|
||||
When sharing setup or run steps for the user to execute, render commands in fenced code blocks with an appropriate language tag (`bash`, `sh`, `powershell`, `python`, etc.). Keep one command per line; avoid prose-only representations of commands.
|
||||
Keep responses conversational and fun—use a brief, friendly preamble that acknowledges the goal and states what you're about to do next. Avoid literal scaffold labels like "Plan:", "Task receipt:", or "Actions:"; instead, use short paragraphs and, when helpful, concise bullet lists. Do not start with filler acknowledgements (e.g., "Sounds good", "Great", "Okay, I will…"). For multi-step tasks, maintain a lightweight checklist implicitly and weave progress into your narration.
|
||||
For section headers in your response, use level-2 Markdown headings (`##`) for top-level sections and level-3 (`###`) for subsections. Choose titles dynamically to match the task and content. Do not hard-code fixed section names; create only the sections that make sense and only when they have non-empty content. Keep headings short and descriptive (e.g., "actions taken", "files changed", "how to run", "performance", "notes"), and order them naturally (actions > artifacts > how to run > performance > notes) when applicable. You may add a tasteful emoji to a heading when it improves scannability; keep it minimal and professional. Headings must start at the beginning of the line with `## ` or `### `, have a blank line before and after, and must not be inside lists, block quotes, or code fences.
|
||||
When listing files created/edited, include a one-line purpose for each file when helpful. In performance sections, base any metrics on actual runs from this session; note the hardware/OS context and mark estimates clearly—never fabricate numbers. In "Try it" sections, keep commands copyable; comments starting with `#` are okay, but put each command on its own line.
|
||||
If platform-specific acceleration applies, include an optional speed-up fenced block with commands. Close with a concise completion summary describing what changed and how it was verified (build/tests/linters), plus any follow-ups.
|
||||
<example>
|
||||
The class `Person` is in `src/models/person.ts`.
|
||||
</example>
|
||||
Use KaTeX for math equations in your answers.
|
||||
Wrap inline math equations in $.
|
||||
Wrap more complex blocks of math equations in $$.
|
||||
|
||||
</outputFormatting>
|
||||
@@ -1,3 +1,8 @@
|
||||
<system-reminder>
|
||||
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supersedes any other instructions you have received (for example, to make edits).
|
||||
Plan mode is active. The user indicated that they do not want you to execute yet
|
||||
-- you MUST NOT make any edits, run any non-readonly tools (including changing
|
||||
configs or making commits), or otherwise make any changes to the system. This
|
||||
supersedes any other instructions you have received (for example, to make
|
||||
edits). Bash tool must only run readonly commands
|
||||
</system-reminder>
|
||||
|
||||
|
||||
@@ -13,13 +13,16 @@ import PROMPT_GEMINI from "./prompt/gemini.txt"
|
||||
import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
|
||||
import PROMPT_SUMMARIZE from "./prompt/summarize.txt"
|
||||
import PROMPT_TITLE from "./prompt/title.txt"
|
||||
import PROMPT_COPILOT_GPT_5 from "./prompt/copilot-gpt-5.txt"
|
||||
|
||||
export namespace SystemPrompt {
|
||||
export function header(providerID: string) {
|
||||
if (providerID.includes("anthropic")) return [PROMPT_ANTHROPIC_SPOOF.trim()]
|
||||
return []
|
||||
}
|
||||
|
||||
export function provider(modelID: string) {
|
||||
if (modelID.includes("gpt-5")) return [PROMPT_COPILOT_GPT_5]
|
||||
if (modelID.includes("gpt-") || modelID.includes("o1") || modelID.includes("o3")) return [PROMPT_BEAST]
|
||||
if (modelID.includes("gemini-")) return [PROMPT_GEMINI]
|
||||
if (modelID.includes("claude")) return [PROMPT_ANTHROPIC]
|
||||
@@ -51,28 +54,53 @@ export namespace SystemPrompt {
|
||||
]
|
||||
}
|
||||
|
||||
const CUSTOM_FILES = [
|
||||
const LOCAL_RULE_FILES = [
|
||||
"AGENTS.md",
|
||||
"CLAUDE.md",
|
||||
"CONTEXT.md", // deprecated
|
||||
]
|
||||
const GLOBAL_RULE_FILES = [
|
||||
path.join(Global.Path.config, "AGENTS.md"),
|
||||
path.join(os.homedir(), ".claude", "CLAUDE.md"),
|
||||
]
|
||||
|
||||
export async function custom() {
|
||||
const { cwd, root } = App.info().path
|
||||
const config = await Config.get()
|
||||
const paths = new Set<string>()
|
||||
|
||||
for (const item of CUSTOM_FILES) {
|
||||
const matches = await Filesystem.findUp(item, cwd, root)
|
||||
matches.forEach((path) => paths.add(path))
|
||||
for (const localRuleFile of LOCAL_RULE_FILES) {
|
||||
const matches = await Filesystem.findUp(localRuleFile, cwd, root)
|
||||
if (matches.length > 0) {
|
||||
matches.forEach((path) => paths.add(path))
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
paths.add(path.join(Global.Path.config, "AGENTS.md"))
|
||||
paths.add(path.join(os.homedir(), ".claude", "CLAUDE.md"))
|
||||
for (const globalRuleFile of GLOBAL_RULE_FILES) {
|
||||
if (await Bun.file(globalRuleFile).exists()) {
|
||||
paths.add(globalRuleFile)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (config.instructions) {
|
||||
for (const instruction of config.instructions) {
|
||||
const matches = await Filesystem.globUp(instruction, cwd, root).catch(() => [])
|
||||
for (let instruction of config.instructions) {
|
||||
if (instruction.startsWith("~/")) {
|
||||
instruction = path.join(os.homedir(), instruction.slice(2))
|
||||
}
|
||||
let matches: string[] = []
|
||||
if (path.isAbsolute(instruction)) {
|
||||
matches = await Array.fromAsync(
|
||||
new Bun.Glob(path.basename(instruction)).scan({
|
||||
cwd: path.dirname(instruction),
|
||||
absolute: true,
|
||||
onlyFiles: true,
|
||||
}),
|
||||
).catch(() => [])
|
||||
} else {
|
||||
matches = await Filesystem.globUp(instruction, cwd, root).catch(() => [])
|
||||
}
|
||||
matches.forEach((path) => paths.add(path))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from "zod"
|
||||
import { exec } from "child_process"
|
||||
import { text } from "stream/consumers"
|
||||
|
||||
import { Tool } from "./tool"
|
||||
import DESCRIPTION from "./bash.txt"
|
||||
import { App } from "../app/app"
|
||||
@@ -130,8 +130,35 @@ export const BashTool = Tool.define("bash", {
|
||||
timeout,
|
||||
})
|
||||
|
||||
const stdoutPromise = text(process.stdout!)
|
||||
const stderrPromise = text(process.stderr!)
|
||||
let output = ""
|
||||
|
||||
// Initialize metadata with empty output
|
||||
ctx.metadata({
|
||||
metadata: {
|
||||
output: "",
|
||||
description: params.description,
|
||||
},
|
||||
})
|
||||
|
||||
process.stdout?.on("data", (chunk) => {
|
||||
output += chunk.toString()
|
||||
ctx.metadata({
|
||||
metadata: {
|
||||
output: output,
|
||||
description: params.description,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
process.stderr?.on("data", (chunk) => {
|
||||
output += chunk.toString()
|
||||
ctx.metadata({
|
||||
metadata: {
|
||||
output: output,
|
||||
description: params.description,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
process.on("close", () => {
|
||||
@@ -139,18 +166,22 @@ export const BashTool = Tool.define("bash", {
|
||||
})
|
||||
})
|
||||
|
||||
const stdout = await stdoutPromise
|
||||
const stderr = await stderrPromise
|
||||
ctx.metadata({
|
||||
metadata: {
|
||||
output: output,
|
||||
exit: process.exitCode,
|
||||
description: params.description,
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
title: params.command,
|
||||
metadata: {
|
||||
stderr,
|
||||
stdout,
|
||||
output,
|
||||
exit: process.exitCode,
|
||||
description: params.description,
|
||||
},
|
||||
output: [`<stdout>`, stdout ?? "", `</stdout>`, `<stderr>`, stderr ?? "", `</stderr>`].join("\n"),
|
||||
output,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
@@ -59,10 +59,6 @@ When the user asks you to create a new git commit, follow these steps carefully:
|
||||
|
||||
3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:
|
||||
- Add relevant untracked files to the staging area.
|
||||
- Create the commit with a message ending with:
|
||||
🤖 Generated with [opencode](https://opencode.ai)
|
||||
|
||||
Co-Authored-By: opencode <noreply@opencode.ai>
|
||||
- Run git status to make sure the commit succeeded.
|
||||
|
||||
4. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.
|
||||
@@ -76,17 +72,6 @@ Important notes:
|
||||
- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
|
||||
- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
|
||||
- Return an empty response - the user will see the git output directly
|
||||
- In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example:
|
||||
<example>
|
||||
git commit -m "$(cat <<'EOF'
|
||||
Commit message here.
|
||||
|
||||
🤖 Generated with [opencode](https://opencode.ai)
|
||||
|
||||
Co-Authored-By: opencode <noreply@opencode.ai>
|
||||
EOF
|
||||
)"
|
||||
</example>
|
||||
|
||||
# Creating pull requests
|
||||
Use the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.
|
||||
@@ -125,14 +110,6 @@ gh pr create --title "the pr title" --body "$(cat <<'EOF'
|
||||
## Summary
|
||||
<1-3 bullet points>
|
||||
|
||||
## Test plan
|
||||
[Checklist of TODOs for testing the pull request...]
|
||||
|
||||
🤖 Generated with [opencode](https://opencode.ai)
|
||||
EOF
|
||||
)"
|
||||
</example>
|
||||
|
||||
Important:
|
||||
- NEVER update the git config
|
||||
- Return the PR URL when you're done, so the user can see it
|
||||
|
||||
@@ -111,6 +111,7 @@ export const EditTool = Tool.define("edit", {
|
||||
continue
|
||||
}
|
||||
output += `\n<project_diagnostics>\n${file}\n${issues
|
||||
// TODO: may want to make more leniant for eslint
|
||||
.filter((item) => item.severity === 1)
|
||||
.map(LSP.Diagnostic.pretty)
|
||||
.join("\n")}\n</project_diagnostics>\n`
|
||||
@@ -187,7 +188,10 @@ export const LineTrimmedReplacer: Replacer = function* (content, find) {
|
||||
|
||||
let matchEndIndex = matchStartIndex
|
||||
for (let k = 0; k < searchLines.length; k++) {
|
||||
matchEndIndex += originalLines[i + k].length + 1
|
||||
matchEndIndex += originalLines[i + k].length
|
||||
if (k < searchLines.length - 1) {
|
||||
matchEndIndex += 1 // Add newline character except for the last line
|
||||
}
|
||||
}
|
||||
|
||||
yield content.substring(matchStartIndex, matchEndIndex)
|
||||
|
||||
@@ -79,6 +79,9 @@ export namespace ToolRegistry {
|
||||
if (cfg?.permission?.bash === "deny") {
|
||||
result["bash"] = false
|
||||
}
|
||||
if (cfg?.permission?.webfetch === "deny") {
|
||||
result["webfetch"] = false
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ import { z } from "zod"
|
||||
import { Tool } from "./tool"
|
||||
import TurndownService from "turndown"
|
||||
import DESCRIPTION from "./webfetch.txt"
|
||||
import { Config } from "../config/config"
|
||||
import { Permission } from "../permission"
|
||||
|
||||
const MAX_RESPONSE_SIZE = 5 * 1024 * 1024 // 5MB
|
||||
const DEFAULT_TIMEOUT = 30 * 1000 // 30 seconds
|
||||
@@ -22,6 +24,21 @@ export const WebFetchTool = Tool.define("webfetch", {
|
||||
throw new Error("URL must start with http:// or https://")
|
||||
}
|
||||
|
||||
const cfg = await Config.get()
|
||||
if (cfg.permission?.webfetch === "ask")
|
||||
await Permission.ask({
|
||||
type: "webfetch",
|
||||
sessionID: ctx.sessionID,
|
||||
messageID: ctx.messageID,
|
||||
callID: ctx.callID,
|
||||
title: "Fetch content from: " + params.url,
|
||||
metadata: {
|
||||
url: params.url,
|
||||
format: params.format,
|
||||
timeout: params.timeout,
|
||||
},
|
||||
})
|
||||
|
||||
const timeout = Math.min((params.timeout ?? DEFAULT_TIMEOUT / 1000) * 1000, MAX_TIMEOUT)
|
||||
|
||||
const controller = new AbortController()
|
||||
|
||||
@@ -27,7 +27,7 @@ describe("tool.bash", () => {
|
||||
ctx,
|
||||
)
|
||||
expect(result.metadata.exit).toBe(0)
|
||||
expect(result.metadata.stdout).toContain("test")
|
||||
expect(result.metadata.output).toContain("test")
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode-ai/plugin",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.22",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
|
||||
@@ -19,7 +19,7 @@ export interface Hooks {
|
||||
*/
|
||||
"chat.params"?: (
|
||||
input: { model: Model; provider: Provider; message: UserMessage },
|
||||
output: { temperature: number; topP: number },
|
||||
output: { temperature: number; topP: number; options: Record<string, any> },
|
||||
) => Promise<void>
|
||||
"permission.ask"?: (input: Permission, output: { status: "ask" | "deny" | "allow" }) => Promise<void>
|
||||
"tool.execute.before"?: (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
configured_endpoints: 34
|
||||
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-da1c340135c3dd6b1edb4e00e7039d2ac54d59271683a8b6ed528e51137ce41a.yml
|
||||
openapi_spec_hash: 0cdd9b6273d72f5a6f484a2999ff0632
|
||||
config_hash: 7581d5948150d4ef7dd7b13d0845dbeb
|
||||
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-b86cf7bb8df4f60ebe8b8f51e281c8076cfdccc8554178c1b78beca4b025f0ff.yml
|
||||
openapi_spec_hash: 47633b7481d91708643ea7b43fffffe6
|
||||
config_hash: bd7f6435ed0c0005f373b5526c07a055
|
||||
|
||||
@@ -92,6 +92,7 @@ Response Types:
|
||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FileSource">FileSource</a>
|
||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Message">Message</a>
|
||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Part">Part</a>
|
||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#ReasoningPart">ReasoningPart</a>
|
||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Session">Session</a>
|
||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#SnapshotPart">SnapshotPart</a>
|
||||
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#StepFinishPart">StepFinishPart</a>
|
||||
|
||||
@@ -74,9 +74,10 @@ type Config struct {
|
||||
// Control sharing behavior:'manual' allows manual sharing via commands, 'auto'
|
||||
// enables automatic sharing, 'disabled' disables all sharing
|
||||
Share ConfigShare `json:"share"`
|
||||
// Small model to use for tasks like title generation in the
|
||||
// format of provider/model
|
||||
// Small model to use for tasks like title generation in the format of
|
||||
// provider/model
|
||||
SmallModel string `json:"small_model"`
|
||||
Snapshot bool `json:"snapshot"`
|
||||
// Theme name to use for the interface
|
||||
Theme string `json:"theme"`
|
||||
// Custom username to display in conversations instead of system username
|
||||
@@ -105,6 +106,7 @@ type configJSON struct {
|
||||
Provider apijson.Field
|
||||
Share apijson.Field
|
||||
SmallModel apijson.Field
|
||||
Snapshot apijson.Field
|
||||
Theme apijson.Field
|
||||
Username apijson.Field
|
||||
raw string
|
||||
@@ -780,9 +782,10 @@ func (r ConfigModePlanMode) IsKnown() bool {
|
||||
}
|
||||
|
||||
type ConfigPermission struct {
|
||||
Bash ConfigPermissionBashUnion `json:"bash"`
|
||||
Edit ConfigPermissionEdit `json:"edit"`
|
||||
JSON configPermissionJSON `json:"-"`
|
||||
Bash ConfigPermissionBashUnion `json:"bash"`
|
||||
Edit ConfigPermissionEdit `json:"edit"`
|
||||
Webfetch ConfigPermissionWebfetch `json:"webfetch"`
|
||||
JSON configPermissionJSON `json:"-"`
|
||||
}
|
||||
|
||||
// configPermissionJSON contains the JSON metadata for the struct
|
||||
@@ -790,6 +793,7 @@ type ConfigPermission struct {
|
||||
type configPermissionJSON struct {
|
||||
Bash apijson.Field
|
||||
Edit apijson.Field
|
||||
Webfetch apijson.Field
|
||||
raw string
|
||||
ExtraFields map[string]apijson.Field
|
||||
}
|
||||
@@ -876,6 +880,22 @@ func (r ConfigPermissionEdit) IsKnown() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
type ConfigPermissionWebfetch string
|
||||
|
||||
const (
|
||||
ConfigPermissionWebfetchAsk ConfigPermissionWebfetch = "ask"
|
||||
ConfigPermissionWebfetchAllow ConfigPermissionWebfetch = "allow"
|
||||
ConfigPermissionWebfetchDeny ConfigPermissionWebfetch = "deny"
|
||||
)
|
||||
|
||||
func (r ConfigPermissionWebfetch) IsKnown() bool {
|
||||
switch r {
|
||||
case ConfigPermissionWebfetchAsk, ConfigPermissionWebfetchAllow, ConfigPermissionWebfetchDeny:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type ConfigProvider struct {
|
||||
Models map[string]ConfigProviderModel `json:"models,required"`
|
||||
ID string `json:"id"`
|
||||
|
||||
@@ -21,7 +21,7 @@ echo "==> Starting mock server with URL ${URL}"
|
||||
|
||||
# Run prism mock on the given spec
|
||||
if [ "$1" == "--daemon" ]; then
|
||||
npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL" &> .prism.log &
|
||||
npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL" &> .prism.log &
|
||||
|
||||
# Wait for server to come online
|
||||
echo -n "Waiting for server"
|
||||
@@ -37,5 +37,5 @@ if [ "$1" == "--daemon" ]; then
|
||||
|
||||
echo
|
||||
else
|
||||
npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL"
|
||||
npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock "$URL"
|
||||
fi
|
||||
|
||||
@@ -43,7 +43,7 @@ elif ! prism_is_running ; then
|
||||
echo -e "To run the server, pass in the path or url of your OpenAPI"
|
||||
echo -e "spec to the prism command:"
|
||||
echo
|
||||
echo -e " \$ ${YELLOW}npm exec --package=@stoplight/prism-cli@~5.3.2 -- prism mock path/to/your.openapi.yml${NC}"
|
||||
echo -e " \$ ${YELLOW}npm exec --package=@stainless-api/prism-cli@5.15.0 -- prism mock path/to/your.openapi.yml${NC}"
|
||||
echo
|
||||
|
||||
exit 1
|
||||
|
||||
+115
-33
@@ -962,18 +962,20 @@ type Part struct {
|
||||
Cost float64 `json:"cost"`
|
||||
Filename string `json:"filename"`
|
||||
// This field can have the runtime type of [[]string].
|
||||
Files interface{} `json:"files"`
|
||||
Hash string `json:"hash"`
|
||||
Mime string `json:"mime"`
|
||||
Name string `json:"name"`
|
||||
Snapshot string `json:"snapshot"`
|
||||
Files interface{} `json:"files"`
|
||||
Hash string `json:"hash"`
|
||||
Mime string `json:"mime"`
|
||||
Name string `json:"name"`
|
||||
// This field can have the runtime type of [map[string]interface{}].
|
||||
ProviderMetadata interface{} `json:"providerMetadata"`
|
||||
Snapshot string `json:"snapshot"`
|
||||
// This field can have the runtime type of [FilePartSource], [AgentPartSource].
|
||||
Source interface{} `json:"source"`
|
||||
// This field can have the runtime type of [ToolPartState].
|
||||
State interface{} `json:"state"`
|
||||
Synthetic bool `json:"synthetic"`
|
||||
Text string `json:"text"`
|
||||
// This field can have the runtime type of [TextPartTime].
|
||||
// This field can have the runtime type of [TextPartTime], [ReasoningPartTime].
|
||||
Time interface{} `json:"time"`
|
||||
// This field can have the runtime type of [StepFinishPartTokens].
|
||||
Tokens interface{} `json:"tokens"`
|
||||
@@ -985,28 +987,29 @@ type Part struct {
|
||||
|
||||
// partJSON contains the JSON metadata for the struct [Part]
|
||||
type partJSON struct {
|
||||
ID apijson.Field
|
||||
MessageID apijson.Field
|
||||
SessionID apijson.Field
|
||||
Type apijson.Field
|
||||
CallID apijson.Field
|
||||
Cost apijson.Field
|
||||
Filename apijson.Field
|
||||
Files apijson.Field
|
||||
Hash apijson.Field
|
||||
Mime apijson.Field
|
||||
Name apijson.Field
|
||||
Snapshot apijson.Field
|
||||
Source apijson.Field
|
||||
State apijson.Field
|
||||
Synthetic apijson.Field
|
||||
Text apijson.Field
|
||||
Time apijson.Field
|
||||
Tokens apijson.Field
|
||||
Tool apijson.Field
|
||||
URL apijson.Field
|
||||
raw string
|
||||
ExtraFields map[string]apijson.Field
|
||||
ID apijson.Field
|
||||
MessageID apijson.Field
|
||||
SessionID apijson.Field
|
||||
Type apijson.Field
|
||||
CallID apijson.Field
|
||||
Cost apijson.Field
|
||||
Filename apijson.Field
|
||||
Files apijson.Field
|
||||
Hash apijson.Field
|
||||
Mime apijson.Field
|
||||
Name apijson.Field
|
||||
ProviderMetadata apijson.Field
|
||||
Snapshot apijson.Field
|
||||
Source apijson.Field
|
||||
State apijson.Field
|
||||
Synthetic apijson.Field
|
||||
Text apijson.Field
|
||||
Time apijson.Field
|
||||
Tokens apijson.Field
|
||||
Tool apijson.Field
|
||||
URL apijson.Field
|
||||
raw string
|
||||
ExtraFields map[string]apijson.Field
|
||||
}
|
||||
|
||||
func (r partJSON) RawJSON() string {
|
||||
@@ -1025,14 +1028,16 @@ func (r *Part) UnmarshalJSON(data []byte) (err error) {
|
||||
// AsUnion returns a [PartUnion] interface which you can cast to the specific types
|
||||
// for more type safety.
|
||||
//
|
||||
// Possible runtime types of the union are [TextPart], [FilePart], [ToolPart],
|
||||
// [StepStartPart], [StepFinishPart], [SnapshotPart], [PartPatchPart], [AgentPart].
|
||||
// Possible runtime types of the union are [TextPart], [ReasoningPart], [FilePart],
|
||||
// [ToolPart], [StepStartPart], [StepFinishPart], [SnapshotPart], [PartPatchPart],
|
||||
// [AgentPart].
|
||||
func (r Part) AsUnion() PartUnion {
|
||||
return r.union
|
||||
}
|
||||
|
||||
// Union satisfied by [TextPart], [FilePart], [ToolPart], [StepStartPart],
|
||||
// [StepFinishPart], [SnapshotPart], [PartPatchPart] or [AgentPart].
|
||||
// Union satisfied by [TextPart], [ReasoningPart], [FilePart], [ToolPart],
|
||||
// [StepStartPart], [StepFinishPart], [SnapshotPart], [PartPatchPart] or
|
||||
// [AgentPart].
|
||||
type PartUnion interface {
|
||||
implementsPart()
|
||||
}
|
||||
@@ -1046,6 +1051,11 @@ func init() {
|
||||
Type: reflect.TypeOf(TextPart{}),
|
||||
DiscriminatorValue: "text",
|
||||
},
|
||||
apijson.UnionVariant{
|
||||
TypeFilter: gjson.JSON,
|
||||
Type: reflect.TypeOf(ReasoningPart{}),
|
||||
DiscriminatorValue: "reasoning",
|
||||
},
|
||||
apijson.UnionVariant{
|
||||
TypeFilter: gjson.JSON,
|
||||
Type: reflect.TypeOf(FilePart{}),
|
||||
@@ -1134,6 +1144,7 @@ type PartType string
|
||||
|
||||
const (
|
||||
PartTypeText PartType = "text"
|
||||
PartTypeReasoning PartType = "reasoning"
|
||||
PartTypeFile PartType = "file"
|
||||
PartTypeTool PartType = "tool"
|
||||
PartTypeStepStart PartType = "step-start"
|
||||
@@ -1145,12 +1156,83 @@ const (
|
||||
|
||||
func (r PartType) IsKnown() bool {
|
||||
switch r {
|
||||
case PartTypeText, PartTypeFile, PartTypeTool, PartTypeStepStart, PartTypeStepFinish, PartTypeSnapshot, PartTypePatch, PartTypeAgent:
|
||||
case PartTypeText, PartTypeReasoning, PartTypeFile, PartTypeTool, PartTypeStepStart, PartTypeStepFinish, PartTypeSnapshot, PartTypePatch, PartTypeAgent:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type ReasoningPart struct {
|
||||
ID string `json:"id,required"`
|
||||
MessageID string `json:"messageID,required"`
|
||||
SessionID string `json:"sessionID,required"`
|
||||
Text string `json:"text,required"`
|
||||
Type ReasoningPartType `json:"type,required"`
|
||||
ProviderMetadata map[string]interface{} `json:"providerMetadata"`
|
||||
Time ReasoningPartTime `json:"time"`
|
||||
JSON reasoningPartJSON `json:"-"`
|
||||
}
|
||||
|
||||
// reasoningPartJSON contains the JSON metadata for the struct [ReasoningPart]
|
||||
type reasoningPartJSON struct {
|
||||
ID apijson.Field
|
||||
MessageID apijson.Field
|
||||
SessionID apijson.Field
|
||||
Text apijson.Field
|
||||
Type apijson.Field
|
||||
ProviderMetadata apijson.Field
|
||||
Time apijson.Field
|
||||
raw string
|
||||
ExtraFields map[string]apijson.Field
|
||||
}
|
||||
|
||||
func (r *ReasoningPart) UnmarshalJSON(data []byte) (err error) {
|
||||
return apijson.UnmarshalRoot(data, r)
|
||||
}
|
||||
|
||||
func (r reasoningPartJSON) RawJSON() string {
|
||||
return r.raw
|
||||
}
|
||||
|
||||
func (r ReasoningPart) implementsPart() {}
|
||||
|
||||
type ReasoningPartType string
|
||||
|
||||
const (
|
||||
ReasoningPartTypeReasoning ReasoningPartType = "reasoning"
|
||||
)
|
||||
|
||||
func (r ReasoningPartType) IsKnown() bool {
|
||||
switch r {
|
||||
case ReasoningPartTypeReasoning:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type ReasoningPartTime struct {
|
||||
Start float64 `json:"start,required"`
|
||||
End float64 `json:"end"`
|
||||
JSON reasoningPartTimeJSON `json:"-"`
|
||||
}
|
||||
|
||||
// reasoningPartTimeJSON contains the JSON metadata for the struct
|
||||
// [ReasoningPartTime]
|
||||
type reasoningPartTimeJSON struct {
|
||||
Start apijson.Field
|
||||
End apijson.Field
|
||||
raw string
|
||||
ExtraFields map[string]apijson.Field
|
||||
}
|
||||
|
||||
func (r *ReasoningPartTime) UnmarshalJSON(data []byte) (err error) {
|
||||
return apijson.UnmarshalRoot(data, r)
|
||||
}
|
||||
|
||||
func (r reasoningPartTimeJSON) RawJSON() string {
|
||||
return r.raw
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
ID string `json:"id,required"`
|
||||
Time SessionTime `json:"time,required"`
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode-ai/sdk",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.22",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
|
||||
@@ -182,6 +182,9 @@ export type Part =
|
||||
| ({
|
||||
type: "text"
|
||||
} & TextPart)
|
||||
| ({
|
||||
type: "reasoning"
|
||||
} & ReasoningPart)
|
||||
| ({
|
||||
type: "file"
|
||||
} & FilePart)
|
||||
@@ -217,6 +220,21 @@ export type TextPart = {
|
||||
}
|
||||
}
|
||||
|
||||
export type ReasoningPart = {
|
||||
id: string
|
||||
sessionID: string
|
||||
messageID: string
|
||||
type: string
|
||||
text: string
|
||||
metadata?: {
|
||||
[key: string]: unknown
|
||||
}
|
||||
time: {
|
||||
start: number
|
||||
end?: number
|
||||
}
|
||||
}
|
||||
|
||||
export type FilePart = {
|
||||
id: string
|
||||
sessionID: string
|
||||
@@ -609,7 +627,7 @@ export type Config = {
|
||||
env?: Array<string>
|
||||
id?: string
|
||||
npm?: string
|
||||
models: {
|
||||
models?: {
|
||||
[key: string]: {
|
||||
id?: string
|
||||
name?: string
|
||||
@@ -691,6 +709,7 @@ export type Config = {
|
||||
| {
|
||||
[key: string]: string
|
||||
}
|
||||
webfetch?: string
|
||||
}
|
||||
experimental?: {
|
||||
hook?: {
|
||||
@@ -773,6 +792,10 @@ export type KeybindsConfig = {
|
||||
* Toggle tool details
|
||||
*/
|
||||
tool_details: string
|
||||
/**
|
||||
* Toggle thinking blocks
|
||||
*/
|
||||
thinking_blocks: string
|
||||
/**
|
||||
* List available models
|
||||
*/
|
||||
@@ -889,6 +912,16 @@ export type AgentConfig = {
|
||||
*/
|
||||
description?: string
|
||||
mode?: string
|
||||
[key: string]:
|
||||
| unknown
|
||||
| string
|
||||
| number
|
||||
| {
|
||||
[key: string]: boolean
|
||||
}
|
||||
| boolean
|
||||
| string
|
||||
| undefined
|
||||
}
|
||||
|
||||
export type Provider = {
|
||||
@@ -1036,6 +1069,9 @@ export type Agent = {
|
||||
tools: {
|
||||
[key: string]: boolean
|
||||
}
|
||||
options: {
|
||||
[key: string]: unknown
|
||||
}
|
||||
}
|
||||
|
||||
export type EventSubscribeData = {
|
||||
|
||||
@@ -101,6 +101,7 @@ resources:
|
||||
toolPart: ToolPart
|
||||
agentPart: AgentPart
|
||||
agentPartInput: AgentPartInput
|
||||
reasoningPart: ReasoningPart
|
||||
stepStartPart: StepStartPart
|
||||
stepFinishPart: StepFinishPart
|
||||
snapshotPart: SnapshotPart
|
||||
|
||||
@@ -32,6 +32,7 @@ func main() {
|
||||
var model *string = flag.String("model", "", "model to begin with")
|
||||
var prompt *string = flag.String("prompt", "", "prompt to begin with")
|
||||
var agent *string = flag.String("agent", "", "agent to begin with")
|
||||
var sessionID *string = flag.String("session", "", "session ID")
|
||||
flag.Parse()
|
||||
|
||||
url := os.Getenv("OPENCODE_SERVER")
|
||||
@@ -96,7 +97,7 @@ func main() {
|
||||
}()
|
||||
|
||||
// Create main context for the application
|
||||
app_, err := app.New(ctx, version, appInfo, agents, httpClient, model, prompt, agent)
|
||||
app_, err := app.New(ctx, version, appInfo, agents, httpClient, model, prompt, agent, sessionID)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ type App struct {
|
||||
InitialModel *string
|
||||
InitialPrompt *string
|
||||
InitialAgent *string
|
||||
InitialSession *string
|
||||
compactCancel context.CancelFunc
|
||||
IsLeaderSequence bool
|
||||
}
|
||||
@@ -70,6 +71,9 @@ type ModelSelectedMsg struct {
|
||||
Provider opencode.Provider
|
||||
Model opencode.Model
|
||||
}
|
||||
type AgentSelectedMsg struct {
|
||||
Agent opencode.Agent
|
||||
}
|
||||
type SessionClearedMsg struct{}
|
||||
type CompactSessionMsg struct{}
|
||||
type SendPrompt = Prompt
|
||||
@@ -92,6 +96,7 @@ func New(
|
||||
initialModel *string,
|
||||
initialPrompt *string,
|
||||
initialAgent *string,
|
||||
initialSession *string,
|
||||
) (*App, error) {
|
||||
util.RootPath = appInfo.Path.Root
|
||||
util.CwdPath = appInfo.Path.Cwd
|
||||
@@ -172,20 +177,21 @@ func New(
|
||||
slog.Debug("Loaded config", "config", configInfo)
|
||||
|
||||
app := &App{
|
||||
Info: appInfo,
|
||||
Agents: agents,
|
||||
Version: version,
|
||||
StatePath: appStatePath,
|
||||
Config: configInfo,
|
||||
State: appState,
|
||||
Client: httpClient,
|
||||
AgentIndex: agentIndex,
|
||||
Session: &opencode.Session{},
|
||||
Messages: []Message{},
|
||||
Commands: commands.LoadFromConfig(configInfo),
|
||||
InitialModel: initialModel,
|
||||
InitialPrompt: initialPrompt,
|
||||
InitialAgent: initialAgent,
|
||||
Info: appInfo,
|
||||
Agents: agents,
|
||||
Version: version,
|
||||
StatePath: appStatePath,
|
||||
Config: configInfo,
|
||||
State: appState,
|
||||
Client: httpClient,
|
||||
AgentIndex: agentIndex,
|
||||
Session: &opencode.Session{},
|
||||
Messages: []Message{},
|
||||
Commands: commands.LoadFromConfig(configInfo),
|
||||
InitialModel: initialModel,
|
||||
InitialPrompt: initialPrompt,
|
||||
InitialAgent: initialAgent,
|
||||
InitialSession: initialSession,
|
||||
}
|
||||
|
||||
return app, nil
|
||||
@@ -277,6 +283,39 @@ func (a *App) SwitchAgentReverse() (*App, tea.Cmd) {
|
||||
return a.cycleMode(false)
|
||||
}
|
||||
|
||||
func (a *App) CycleRecentModel() (*App, tea.Cmd) {
|
||||
recentModels := a.State.RecentlyUsedModels
|
||||
if len(recentModels) > 5 {
|
||||
recentModels = recentModels[:5]
|
||||
}
|
||||
if len(recentModels) < 2 {
|
||||
return a, toast.NewInfoToast("Need at least 2 recent models to cycle")
|
||||
}
|
||||
nextIndex := 0
|
||||
for i, recentModel := range recentModels {
|
||||
if a.Provider != nil && a.Model != nil && recentModel.ProviderID == a.Provider.ID && recentModel.ModelID == a.Model.ID {
|
||||
nextIndex = (i + 1) % len(recentModels)
|
||||
break
|
||||
}
|
||||
}
|
||||
for range recentModels {
|
||||
currentRecentModel := recentModels[nextIndex%len(recentModels)]
|
||||
provider, model := findModelByProviderAndModelID(a.Providers, currentRecentModel.ProviderID, currentRecentModel.ModelID)
|
||||
if provider != nil && model != nil {
|
||||
a.Provider, a.Model = provider, model
|
||||
a.State.AgentModel[a.Agent().Name] = AgentModel{ProviderID: provider.ID, ModelID: model.ID}
|
||||
return a, tea.Sequence(a.SaveState(), toast.NewSuccessToast(fmt.Sprintf("Switched to %s (%s)", model.Name, provider.Name)))
|
||||
}
|
||||
recentModels = append(recentModels[:nextIndex%len(recentModels)], recentModels[nextIndex%len(recentModels)+1:]...)
|
||||
if len(recentModels) < 2 {
|
||||
a.State.RecentlyUsedModels = recentModels
|
||||
return a, tea.Sequence(a.SaveState(), toast.NewInfoToast("Not enough valid recent models to cycle"))
|
||||
}
|
||||
}
|
||||
a.State.RecentlyUsedModels = recentModels
|
||||
return a, toast.NewErrorToast("Recent model not found")
|
||||
}
|
||||
|
||||
// findModelByFullID finds a model by its full ID in the format "provider/model"
|
||||
func findModelByFullID(
|
||||
providers []opencode.Provider,
|
||||
@@ -381,7 +420,18 @@ func (a *App) InitializeProvider() tea.Cmd {
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 3: Recent model usage (most recently used model)
|
||||
// Priority 3: Current agent's preferred model
|
||||
if selectedProvider == nil && a.Agent().Model.ModelID != "" {
|
||||
if provider, model := findModelByProviderAndModelID(providers, a.Agent().Model.ProviderID, a.Agent().Model.ModelID); provider != nil && model != nil {
|
||||
selectedProvider = provider
|
||||
selectedModel = model
|
||||
slog.Debug("Selected model from current agent", "provider", provider.ID, "model", model.ID, "agent", a.Agent().Name)
|
||||
} else {
|
||||
slog.Debug("Agent model not found", "provider", a.Agent().Model.ProviderID, "model", a.Agent().Model.ModelID, "agent", a.Agent().Name)
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 4: Recent model usage (most recently used model)
|
||||
if selectedProvider == nil && len(a.State.RecentlyUsedModels) > 0 {
|
||||
recentUsage := a.State.RecentlyUsedModels[0] // Most recent is first
|
||||
if provider, model := findModelByProviderAndModelID(providers, recentUsage.ProviderID, recentUsage.ModelID); provider != nil &&
|
||||
@@ -400,7 +450,7 @@ func (a *App) InitializeProvider() tea.Cmd {
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 4: State-based model (backwards compatibility)
|
||||
// Priority 5: State-based model (backwards compatibility)
|
||||
if selectedProvider == nil && a.State.Provider != "" && a.State.Model != "" {
|
||||
if provider, model := findModelByProviderAndModelID(providers, a.State.Provider, a.State.Model); provider != nil &&
|
||||
model != nil {
|
||||
@@ -412,7 +462,7 @@ func (a *App) InitializeProvider() tea.Cmd {
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 5: Internal priority fallback (Anthropic preferred, then first available)
|
||||
// Priority 6: Internal priority fallback (Anthropic preferred, then first available)
|
||||
if selectedProvider == nil {
|
||||
// Try Anthropic first as internal priority
|
||||
if provider := findProviderByID(providers, "anthropic"); provider != nil {
|
||||
@@ -457,6 +507,28 @@ func (a *App) InitializeProvider() tea.Cmd {
|
||||
Provider: *selectedProvider,
|
||||
Model: *selectedModel,
|
||||
}))
|
||||
|
||||
// Load initial session if provided
|
||||
if a.InitialSession != nil && *a.InitialSession != "" {
|
||||
cmds = append(cmds, func() tea.Msg {
|
||||
// Find the session by ID
|
||||
sessions, err := a.ListSessions(context.Background())
|
||||
if err != nil {
|
||||
slog.Error("Failed to list sessions for initial session", "error", err)
|
||||
return toast.NewErrorToast("Failed to load initial session")()
|
||||
}
|
||||
|
||||
for _, session := range sessions {
|
||||
if session.ID == *a.InitialSession {
|
||||
return SessionSelectedMsg(&session)
|
||||
}
|
||||
}
|
||||
|
||||
slog.Warn("Initial session not found", "sessionID", *a.InitialSession)
|
||||
return toast.NewErrorToast("Session not found: " + *a.InitialSession)()
|
||||
})
|
||||
}
|
||||
|
||||
if a.InitialPrompt != nil && *a.InitialPrompt != "" {
|
||||
cmds = append(cmds, util.CmdHandler(SendPrompt{Text: *a.InitialPrompt}))
|
||||
}
|
||||
|
||||
@@ -32,6 +32,8 @@ type State struct {
|
||||
MessagesRight bool `toml:"messages_right"`
|
||||
SplitDiff bool `toml:"split_diff"`
|
||||
MessageHistory []Prompt `toml:"message_history"`
|
||||
ShowToolDetails *bool `toml:"show_tool_details"`
|
||||
ShowThinkingBlocks *bool `toml:"show_thinking_blocks"`
|
||||
}
|
||||
|
||||
func NewState() *State {
|
||||
|
||||
@@ -64,12 +64,13 @@ func (r CommandRegistry) Sorted() []Command {
|
||||
commands = append(commands, command)
|
||||
}
|
||||
slices.SortFunc(commands, func(a, b Command) int {
|
||||
// Priority order: session_new, session_share, model_list, app_help first, app_exit last
|
||||
// Priority order: session_new, session_share, model_list, agent_list, app_help first, app_exit last
|
||||
priorityOrder := map[CommandName]int{
|
||||
SessionNewCommand: 0,
|
||||
AppHelpCommand: 1,
|
||||
SessionShareCommand: 2,
|
||||
ModelListCommand: 3,
|
||||
AgentListCommand: 4,
|
||||
}
|
||||
|
||||
aPriority, aHasPriority := priorityOrder[a.Name]
|
||||
@@ -118,7 +119,10 @@ const (
|
||||
SessionCompactCommand CommandName = "session_compact"
|
||||
SessionExportCommand CommandName = "session_export"
|
||||
ToolDetailsCommand CommandName = "tool_details"
|
||||
ThinkingBlocksCommand CommandName = "thinking_blocks"
|
||||
ModelListCommand CommandName = "model_list"
|
||||
AgentListCommand CommandName = "agent_list"
|
||||
ModelCycleRecentCommand CommandName = "model_cycle_recent"
|
||||
ThemeListCommand CommandName = "theme_list"
|
||||
FileListCommand CommandName = "file_list"
|
||||
FileCloseCommand CommandName = "file_close"
|
||||
@@ -242,12 +246,29 @@ func LoadFromConfig(config *opencode.Config) CommandRegistry {
|
||||
Keybindings: parseBindings("<leader>d"),
|
||||
Trigger: []string{"details"},
|
||||
},
|
||||
{
|
||||
Name: ThinkingBlocksCommand,
|
||||
Description: "toggle thinking blocks",
|
||||
Keybindings: parseBindings("<leader>b"),
|
||||
Trigger: []string{"thinking"},
|
||||
},
|
||||
{
|
||||
Name: ModelListCommand,
|
||||
Description: "list models",
|
||||
Keybindings: parseBindings("<leader>m"),
|
||||
Trigger: []string{"models"},
|
||||
},
|
||||
{
|
||||
Name: AgentListCommand,
|
||||
Description: "list agents",
|
||||
Keybindings: parseBindings("<leader>a"),
|
||||
Trigger: []string{"agents"},
|
||||
},
|
||||
{
|
||||
Name: ModelCycleRecentCommand,
|
||||
Description: "cycle recent models",
|
||||
Keybindings: parseBindings("f2"),
|
||||
},
|
||||
{
|
||||
Name: ThemeListCommand,
|
||||
Description: "list themes",
|
||||
|
||||
@@ -208,6 +208,7 @@ func renderText(
|
||||
showToolDetails bool,
|
||||
width int,
|
||||
extra string,
|
||||
isThinking bool,
|
||||
fileParts []opencode.FilePart,
|
||||
agentParts []opencode.AgentPart,
|
||||
toolCalls ...opencode.ToolPart,
|
||||
@@ -219,8 +220,18 @@ func renderText(
|
||||
var content string
|
||||
switch casted := message.(type) {
|
||||
case opencode.AssistantMessage:
|
||||
backgroundColor = t.Background()
|
||||
if isThinking {
|
||||
backgroundColor = t.BackgroundPanel()
|
||||
}
|
||||
ts = time.UnixMilli(int64(casted.Time.Created))
|
||||
content = util.ToMarkdown(text, width, t.Background())
|
||||
if casted.Time.Completed > 0 {
|
||||
ts = time.UnixMilli(int64(casted.Time.Completed))
|
||||
}
|
||||
content = util.ToMarkdown(text, width, backgroundColor)
|
||||
if isThinking {
|
||||
content = styles.NewStyle().Background(backgroundColor).Foreground(t.TextMuted()).Render("Thinking") + "\n\n" + content
|
||||
}
|
||||
case opencode.UserMessage:
|
||||
ts = time.UnixMilli(int64(casted.Time.Created))
|
||||
base := styles.NewStyle().Foreground(t.Text()).Background(backgroundColor)
|
||||
@@ -324,11 +335,46 @@ func renderText(
|
||||
if time.Now().Format("02 Jan 2006") == timestamp[:11] {
|
||||
timestamp = timestamp[12:]
|
||||
}
|
||||
info := fmt.Sprintf("%s (%s)", author, timestamp)
|
||||
info = styles.NewStyle().Foreground(t.TextMuted()).Render(info)
|
||||
timestamp = styles.NewStyle().
|
||||
Background(backgroundColor).
|
||||
Foreground(t.TextMuted()).
|
||||
Render(" (" + timestamp + ")")
|
||||
|
||||
// Check if this is an assistant message with agent information
|
||||
var modelAndAgentSuffix string
|
||||
if assistantMsg, ok := message.(opencode.AssistantMessage); ok && assistantMsg.Mode != "" {
|
||||
// Find the agent index by name to get the correct color
|
||||
var agentIndex int
|
||||
for i, agent := range app.Agents {
|
||||
if agent.Name == assistantMsg.Mode {
|
||||
agentIndex = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Get agent color based on the original agent index (same as status bar)
|
||||
agentColor := util.GetAgentColor(agentIndex)
|
||||
|
||||
// Style the agent name with the same color as status bar
|
||||
agentName := cases.Title(language.Und).String(assistantMsg.Mode)
|
||||
styledAgentName := styles.NewStyle().
|
||||
Background(backgroundColor).
|
||||
Foreground(agentColor).
|
||||
Render(agentName + " ")
|
||||
styledModelID := styles.NewStyle().
|
||||
Background(backgroundColor).
|
||||
Foreground(t.TextMuted()).
|
||||
Render(assistantMsg.ModelID)
|
||||
modelAndAgentSuffix = styledAgentName + styledModelID
|
||||
}
|
||||
|
||||
var info string
|
||||
if modelAndAgentSuffix != "" {
|
||||
info = modelAndAgentSuffix + timestamp
|
||||
} else {
|
||||
info = author + timestamp
|
||||
}
|
||||
if !showToolDetails && toolCalls != nil && len(toolCalls) > 0 {
|
||||
content = content + "\n\n"
|
||||
for _, toolCall := range toolCalls {
|
||||
title := renderToolTitle(toolCall, width-2)
|
||||
style := styles.NewStyle()
|
||||
@@ -336,15 +382,16 @@ func renderText(
|
||||
style = style.Foreground(t.Error())
|
||||
}
|
||||
title = style.Render(title)
|
||||
title = "∟ " + title + "\n"
|
||||
title = "\n∟ " + title
|
||||
content = content + title
|
||||
}
|
||||
}
|
||||
|
||||
sections := []string{content, info}
|
||||
sections := []string{content}
|
||||
if extra != "" {
|
||||
sections = append(sections, "\n"+extra)
|
||||
sections = append(sections, "\n"+extra+"\n")
|
||||
}
|
||||
sections = append(sections, info)
|
||||
content = strings.Join(sections, "\n")
|
||||
|
||||
switch message.(type) {
|
||||
@@ -357,6 +404,16 @@ func renderText(
|
||||
WithBorderColor(t.Secondary()),
|
||||
)
|
||||
case opencode.AssistantMessage:
|
||||
if isThinking {
|
||||
return renderContentBlock(
|
||||
app,
|
||||
content,
|
||||
width,
|
||||
WithTextColor(t.Text()),
|
||||
WithBackgroundColor(t.BackgroundPanel()),
|
||||
WithBorderColor(t.BackgroundPanel()),
|
||||
)
|
||||
}
|
||||
return renderContentBlock(
|
||||
app,
|
||||
content,
|
||||
@@ -523,13 +580,9 @@ func renderToolDetails(
|
||||
case "bash":
|
||||
command := toolInputMap["command"].(string)
|
||||
body = fmt.Sprintf("```console\n$ %s\n", command)
|
||||
stdout := metadata["stdout"]
|
||||
if stdout != nil {
|
||||
body += ansi.Strip(fmt.Sprintf("%s", stdout))
|
||||
}
|
||||
stderr := metadata["stderr"]
|
||||
if stderr != nil {
|
||||
body += ansi.Strip(fmt.Sprintf("%s", stderr))
|
||||
output := metadata["output"]
|
||||
if output != nil {
|
||||
body += ansi.Strip(fmt.Sprintf("%s", output))
|
||||
}
|
||||
body += "```"
|
||||
body = util.ToMarkdown(body, width, backgroundColor)
|
||||
|
||||
@@ -33,6 +33,7 @@ type MessagesComponent interface {
|
||||
HalfPageUp() (tea.Model, tea.Cmd)
|
||||
HalfPageDown() (tea.Model, tea.Cmd)
|
||||
ToolDetailsVisible() bool
|
||||
ThinkingBlocksVisible() bool
|
||||
GotoTop() (tea.Model, tea.Cmd)
|
||||
GotoBottom() (tea.Model, tea.Cmd)
|
||||
CopyLastMessage() (tea.Model, tea.Cmd)
|
||||
@@ -41,20 +42,21 @@ type MessagesComponent interface {
|
||||
}
|
||||
|
||||
type messagesComponent struct {
|
||||
width, height int
|
||||
app *app.App
|
||||
header string
|
||||
viewport viewport.Model
|
||||
clipboard []string
|
||||
cache *PartCache
|
||||
loading bool
|
||||
showToolDetails bool
|
||||
rendering bool
|
||||
dirty bool
|
||||
tail bool
|
||||
partCount int
|
||||
lineCount int
|
||||
selection *selection
|
||||
width, height int
|
||||
app *app.App
|
||||
header string
|
||||
viewport viewport.Model
|
||||
clipboard []string
|
||||
cache *PartCache
|
||||
loading bool
|
||||
showToolDetails bool
|
||||
showThinkingBlocks bool
|
||||
rendering bool
|
||||
dirty bool
|
||||
tail bool
|
||||
partCount int
|
||||
lineCount int
|
||||
selection *selection
|
||||
}
|
||||
|
||||
type selection struct {
|
||||
@@ -94,6 +96,7 @@ func (s selection) coords(offset int) *selection {
|
||||
}
|
||||
|
||||
type ToggleToolDetailsMsg struct{}
|
||||
type ToggleThinkingBlocksMsg struct{}
|
||||
|
||||
func (m *messagesComponent) Init() tea.Cmd {
|
||||
return tea.Batch(m.viewport.Init())
|
||||
@@ -160,7 +163,12 @@ func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
return m, m.renderView()
|
||||
case ToggleToolDetailsMsg:
|
||||
m.showToolDetails = !m.showToolDetails
|
||||
return m, m.renderView()
|
||||
m.app.State.ShowToolDetails = &m.showToolDetails
|
||||
return m, tea.Batch(m.renderView(), m.app.SaveState())
|
||||
case ToggleThinkingBlocksMsg:
|
||||
m.showThinkingBlocks = !m.showThinkingBlocks
|
||||
m.app.State.ShowThinkingBlocks = &m.showThinkingBlocks
|
||||
return m, tea.Batch(m.renderView(), m.app.SaveState())
|
||||
case app.SessionLoadedMsg, app.SessionClearedMsg:
|
||||
m.cache.Clear()
|
||||
m.tail = true
|
||||
@@ -187,6 +195,10 @@ func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
if msg.Properties.Info.SessionID == m.app.Session.ID {
|
||||
cmds = append(cmds, m.renderView())
|
||||
}
|
||||
case opencode.EventListResponseEventSessionError:
|
||||
if msg.Properties.SessionID == m.app.Session.ID {
|
||||
cmds = append(cmds, m.renderView())
|
||||
}
|
||||
case opencode.EventListResponseEventMessagePartUpdated:
|
||||
if msg.Properties.Part.SessionID == m.app.Session.ID {
|
||||
cmds = append(cmds, m.renderView())
|
||||
@@ -285,6 +297,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
for _, message := range m.app.Messages {
|
||||
var content string
|
||||
var cached bool
|
||||
error := ""
|
||||
|
||||
switch casted := message.Info.(type) {
|
||||
case opencode.UserMessage:
|
||||
@@ -369,6 +382,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
m.showToolDetails,
|
||||
width,
|
||||
files,
|
||||
false,
|
||||
fileParts,
|
||||
agentParts,
|
||||
)
|
||||
@@ -395,6 +409,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
revertedToolCount = 0
|
||||
}
|
||||
hasTextPart := false
|
||||
hasContent := false
|
||||
for partIndex, p := range message.Parts {
|
||||
switch part := p.(type) {
|
||||
case opencode.TextPart:
|
||||
@@ -437,7 +452,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
}
|
||||
|
||||
if finished {
|
||||
key := m.cache.GenerateKey(casted.ID, part.Text, width, m.showToolDetails)
|
||||
key := m.cache.GenerateKey(casted.ID, part.Text, width, m.showToolDetails, toolCallParts)
|
||||
content, cached = m.cache.Get(key)
|
||||
if !cached {
|
||||
content = renderText(
|
||||
@@ -448,6 +463,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
m.showToolDetails,
|
||||
width,
|
||||
"",
|
||||
false,
|
||||
[]opencode.FilePart{},
|
||||
[]opencode.AgentPart{},
|
||||
toolCallParts...,
|
||||
@@ -469,6 +485,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
m.showToolDetails,
|
||||
width,
|
||||
"",
|
||||
false,
|
||||
[]opencode.FilePart{},
|
||||
[]opencode.AgentPart{},
|
||||
toolCallParts...,
|
||||
@@ -484,6 +501,7 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
partCount++
|
||||
lineCount += lipgloss.Height(content) + 1
|
||||
blocks = append(blocks, content)
|
||||
hasContent = true
|
||||
}
|
||||
case opencode.ToolPart:
|
||||
if reverted {
|
||||
@@ -545,14 +563,44 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
partCount++
|
||||
lineCount += lipgloss.Height(content) + 1
|
||||
blocks = append(blocks, content)
|
||||
hasContent = true
|
||||
}
|
||||
case opencode.ReasoningPart:
|
||||
if reverted {
|
||||
continue
|
||||
}
|
||||
if !m.showThinkingBlocks {
|
||||
continue
|
||||
}
|
||||
if part.Text != "" {
|
||||
text := part.Text
|
||||
content = renderText(
|
||||
m.app,
|
||||
message.Info,
|
||||
text,
|
||||
casted.ModelID,
|
||||
m.showToolDetails,
|
||||
width,
|
||||
"",
|
||||
true,
|
||||
[]opencode.FilePart{},
|
||||
[]opencode.AgentPart{},
|
||||
)
|
||||
content = lipgloss.PlaceHorizontal(
|
||||
m.width,
|
||||
lipgloss.Center,
|
||||
content,
|
||||
styles.WhitespaceStyle(t.Background()),
|
||||
)
|
||||
partCount++
|
||||
lineCount += lipgloss.Height(content) + 1
|
||||
blocks = append(blocks, content)
|
||||
hasContent = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
error := ""
|
||||
if assistant, ok := message.Info.(opencode.AssistantMessage); ok {
|
||||
switch err := assistant.Error.AsUnion().(type) {
|
||||
switch err := casted.Error.AsUnion().(type) {
|
||||
case nil:
|
||||
case opencode.AssistantMessageErrorMessageOutputLengthError:
|
||||
error = "Message output length exceeded"
|
||||
@@ -563,6 +611,30 @@ func (m *messagesComponent) renderView() tea.Cmd {
|
||||
case opencode.UnknownError:
|
||||
error = err.Data.Message
|
||||
}
|
||||
|
||||
if !hasContent && error == "" && !reverted {
|
||||
content = renderText(
|
||||
m.app,
|
||||
message.Info,
|
||||
"Generating...",
|
||||
casted.ModelID,
|
||||
m.showToolDetails,
|
||||
width,
|
||||
"",
|
||||
false,
|
||||
[]opencode.FilePart{},
|
||||
[]opencode.AgentPart{},
|
||||
)
|
||||
content = lipgloss.PlaceHorizontal(
|
||||
m.width,
|
||||
lipgloss.Center,
|
||||
content,
|
||||
styles.WhitespaceStyle(t.Background()),
|
||||
)
|
||||
partCount++
|
||||
lineCount += lipgloss.Height(content) + 1
|
||||
blocks = append(blocks, content)
|
||||
}
|
||||
}
|
||||
|
||||
if error != "" && !reverted {
|
||||
@@ -944,6 +1016,10 @@ func (m *messagesComponent) ToolDetailsVisible() bool {
|
||||
return m.showToolDetails
|
||||
}
|
||||
|
||||
func (m *messagesComponent) ThinkingBlocksVisible() bool {
|
||||
return m.showThinkingBlocks
|
||||
}
|
||||
|
||||
func (m *messagesComponent) GotoTop() (tea.Model, tea.Cmd) {
|
||||
m.viewport.GotoTop()
|
||||
return m, nil
|
||||
@@ -1140,11 +1216,23 @@ func NewMessagesComponent(app *app.App) MessagesComponent {
|
||||
vp.MouseWheelDelta = 4
|
||||
}
|
||||
|
||||
// Default to showing tool details, hidden thinking blocks
|
||||
showToolDetails := true
|
||||
if app.State.ShowToolDetails != nil {
|
||||
showToolDetails = *app.State.ShowToolDetails
|
||||
}
|
||||
|
||||
showThinkingBlocks := false
|
||||
if app.State.ShowThinkingBlocks != nil {
|
||||
showThinkingBlocks = *app.State.ShowThinkingBlocks
|
||||
}
|
||||
|
||||
return &messagesComponent{
|
||||
app: app,
|
||||
viewport: vp,
|
||||
showToolDetails: true,
|
||||
cache: NewPartCache(),
|
||||
tail: true,
|
||||
app: app,
|
||||
viewport: vp,
|
||||
showToolDetails: showToolDetails,
|
||||
showThinkingBlocks: showThinkingBlocks,
|
||||
cache: NewPartCache(),
|
||||
tail: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
package dialog
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/charmbracelet/bubbles/v2/key"
|
||||
tea "github.com/charmbracelet/bubbletea/v2"
|
||||
"github.com/lithammer/fuzzysearch/fuzzy"
|
||||
"github.com/sst/opencode-sdk-go"
|
||||
"github.com/sst/opencode/internal/app"
|
||||
"github.com/sst/opencode/internal/components/list"
|
||||
"github.com/sst/opencode/internal/components/modal"
|
||||
"github.com/sst/opencode/internal/layout"
|
||||
"github.com/sst/opencode/internal/styles"
|
||||
"github.com/sst/opencode/internal/theme"
|
||||
"github.com/sst/opencode/internal/util"
|
||||
)
|
||||
|
||||
const (
|
||||
numVisibleAgents = 10
|
||||
minAgentDialogWidth = 54
|
||||
maxAgentDialogWidth = 108
|
||||
maxDescriptionLength = 80
|
||||
)
|
||||
|
||||
// AgentDialog interface for the agent selection dialog
|
||||
type AgentDialog interface {
|
||||
layout.Modal
|
||||
}
|
||||
|
||||
type agentDialog struct {
|
||||
app *app.App
|
||||
allAgents []opencode.Agent
|
||||
width int
|
||||
height int
|
||||
modal *modal.Modal
|
||||
searchDialog *SearchDialog
|
||||
dialogWidth int
|
||||
}
|
||||
|
||||
// agentItem is a custom list item for agent selections
|
||||
type agentItem struct {
|
||||
agent opencode.Agent
|
||||
}
|
||||
|
||||
func (a agentItem) Render(
|
||||
selected bool,
|
||||
width int,
|
||||
baseStyle styles.Style,
|
||||
) string {
|
||||
t := theme.CurrentTheme()
|
||||
|
||||
itemStyle := baseStyle.
|
||||
Background(t.BackgroundPanel()).
|
||||
Foreground(t.Text())
|
||||
|
||||
if selected {
|
||||
itemStyle = itemStyle.Foreground(t.Primary())
|
||||
}
|
||||
|
||||
descStyle := baseStyle.
|
||||
Foreground(t.TextMuted()).
|
||||
Background(t.BackgroundPanel())
|
||||
|
||||
// Calculate available width (accounting for padding and margins)
|
||||
availableWidth := width - 2 // Account for left padding
|
||||
|
||||
agentName := a.agent.Name
|
||||
description := a.agent.Description
|
||||
if description == "" {
|
||||
description = fmt.Sprintf("(%s)", a.agent.Mode)
|
||||
}
|
||||
|
||||
separator := " - "
|
||||
|
||||
// Calculate how much space we have for the description
|
||||
nameAndSeparatorLength := len(agentName) + len(separator)
|
||||
descriptionMaxLength := availableWidth - nameAndSeparatorLength
|
||||
|
||||
// Truncate description if it's too long
|
||||
if len(description) > descriptionMaxLength && descriptionMaxLength > 3 {
|
||||
description = description[:descriptionMaxLength-3] + "..."
|
||||
}
|
||||
|
||||
namePart := itemStyle.Render(agentName)
|
||||
descPart := descStyle.Render(separator + description)
|
||||
combinedText := namePart + descPart
|
||||
|
||||
return baseStyle.
|
||||
Background(t.BackgroundPanel()).
|
||||
PaddingLeft(1).
|
||||
Width(width).
|
||||
Render(combinedText)
|
||||
}
|
||||
|
||||
func (a agentItem) Selectable() bool {
|
||||
// All agents in the dialog are selectable (subagents are filtered out)
|
||||
return true
|
||||
}
|
||||
|
||||
type agentKeyMap struct {
|
||||
Enter key.Binding
|
||||
Escape key.Binding
|
||||
}
|
||||
|
||||
var agentKeys = agentKeyMap{
|
||||
Enter: key.NewBinding(
|
||||
key.WithKeys("enter"),
|
||||
key.WithHelp("enter", "select agent"),
|
||||
),
|
||||
Escape: key.NewBinding(
|
||||
key.WithKeys("esc"),
|
||||
key.WithHelp("esc", "close"),
|
||||
),
|
||||
}
|
||||
|
||||
func (a *agentDialog) Init() tea.Cmd {
|
||||
a.setupAllAgents()
|
||||
return a.searchDialog.Init()
|
||||
}
|
||||
|
||||
func (a *agentDialog) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case SearchSelectionMsg:
|
||||
// Handle selection from search dialog
|
||||
if item, ok := msg.Item.(agentItem); ok {
|
||||
return a, tea.Sequence(
|
||||
util.CmdHandler(modal.CloseModalMsg{}),
|
||||
util.CmdHandler(
|
||||
app.AgentSelectedMsg{
|
||||
Agent: item.agent,
|
||||
}),
|
||||
)
|
||||
}
|
||||
return a, util.CmdHandler(modal.CloseModalMsg{})
|
||||
case SearchCancelledMsg:
|
||||
return a, util.CmdHandler(modal.CloseModalMsg{})
|
||||
|
||||
case SearchQueryChangedMsg:
|
||||
// Update the list based on search query
|
||||
items := a.buildDisplayList(msg.Query)
|
||||
a.searchDialog.SetItems(items)
|
||||
return a, nil
|
||||
|
||||
case tea.WindowSizeMsg:
|
||||
a.width = msg.Width
|
||||
a.height = msg.Height
|
||||
a.searchDialog.SetWidth(a.dialogWidth)
|
||||
a.searchDialog.SetHeight(msg.Height)
|
||||
}
|
||||
|
||||
updatedDialog, cmd := a.searchDialog.Update(msg)
|
||||
a.searchDialog = updatedDialog.(*SearchDialog)
|
||||
return a, cmd
|
||||
}
|
||||
|
||||
func (a *agentDialog) View() string {
|
||||
return a.searchDialog.View()
|
||||
}
|
||||
|
||||
func (a *agentDialog) calculateOptimalWidth(agents []opencode.Agent) int {
|
||||
maxWidth := minAgentDialogWidth
|
||||
|
||||
for _, agent := range agents {
|
||||
// Calculate the width needed for this item: "AgentName - Description"
|
||||
itemWidth := len(agent.Name)
|
||||
if agent.Description != "" {
|
||||
itemWidth += len(agent.Description) + 3 // " - "
|
||||
} else {
|
||||
itemWidth += len(string(agent.Mode)) + 3 // " (mode)"
|
||||
}
|
||||
|
||||
if itemWidth > maxWidth {
|
||||
maxWidth = itemWidth
|
||||
}
|
||||
}
|
||||
|
||||
maxWidth = min(maxWidth, maxAgentDialogWidth)
|
||||
|
||||
return maxWidth
|
||||
}
|
||||
|
||||
func (a *agentDialog) setupAllAgents() {
|
||||
// Get agents from the app, filtering out subagents
|
||||
a.allAgents = []opencode.Agent{}
|
||||
for _, agent := range a.app.Agents {
|
||||
if agent.Mode != "subagent" {
|
||||
a.allAgents = append(a.allAgents, agent)
|
||||
}
|
||||
}
|
||||
|
||||
a.sortAgents()
|
||||
|
||||
// Calculate optimal width based on all agents
|
||||
a.dialogWidth = a.calculateOptimalWidth(a.allAgents)
|
||||
|
||||
// Ensure minimum width to prevent textinput issues
|
||||
a.dialogWidth = max(a.dialogWidth, minAgentDialogWidth)
|
||||
|
||||
a.searchDialog = NewSearchDialog("Search agents...", numVisibleAgents)
|
||||
a.searchDialog.SetWidth(a.dialogWidth)
|
||||
|
||||
items := a.buildDisplayList("")
|
||||
a.searchDialog.SetItems(items)
|
||||
}
|
||||
|
||||
func (a *agentDialog) sortAgents() {
|
||||
sort.Slice(a.allAgents, func(i, j int) bool {
|
||||
agentA := a.allAgents[i]
|
||||
agentB := a.allAgents[j]
|
||||
|
||||
// Current agent goes first
|
||||
if agentA.Name == a.app.Agent().Name {
|
||||
return true
|
||||
}
|
||||
if agentB.Name == a.app.Agent().Name {
|
||||
return false
|
||||
}
|
||||
|
||||
// Alphabetical order for all other agents
|
||||
return agentA.Name < agentB.Name
|
||||
})
|
||||
}
|
||||
|
||||
func (a *agentDialog) buildDisplayList(query string) []list.Item {
|
||||
if query != "" {
|
||||
return a.buildSearchResults(query)
|
||||
}
|
||||
return a.buildGroupedResults()
|
||||
}
|
||||
|
||||
func (a *agentDialog) buildSearchResults(query string) []list.Item {
|
||||
agentNames := []string{}
|
||||
agentMap := make(map[string]opencode.Agent)
|
||||
|
||||
for _, agent := range a.allAgents {
|
||||
// Search by name
|
||||
searchStr := agent.Name
|
||||
agentNames = append(agentNames, searchStr)
|
||||
agentMap[searchStr] = agent
|
||||
|
||||
// Search by description if available
|
||||
if agent.Description != "" {
|
||||
searchStr = fmt.Sprintf("%s %s", agent.Name, agent.Description)
|
||||
agentNames = append(agentNames, searchStr)
|
||||
agentMap[searchStr] = agent
|
||||
}
|
||||
}
|
||||
|
||||
matches := fuzzy.RankFindFold(query, agentNames)
|
||||
sort.Sort(matches)
|
||||
|
||||
items := []list.Item{}
|
||||
seenAgents := make(map[string]bool)
|
||||
|
||||
for _, match := range matches {
|
||||
agent := agentMap[match.Target]
|
||||
// Create a unique key to avoid duplicates
|
||||
key := agent.Name
|
||||
if seenAgents[key] {
|
||||
continue
|
||||
}
|
||||
seenAgents[key] = true
|
||||
items = append(items, agentItem{agent: agent})
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
func (a *agentDialog) buildGroupedResults() []list.Item {
|
||||
var items []list.Item
|
||||
|
||||
items = append(items, list.HeaderItem("Agents"))
|
||||
|
||||
// Add all agents (subagents are already filtered out)
|
||||
for _, agent := range a.allAgents {
|
||||
items = append(items, agentItem{agent: agent})
|
||||
}
|
||||
|
||||
return items
|
||||
}
|
||||
|
||||
func (a *agentDialog) Render(background string) string {
|
||||
return a.modal.Render(a.View(), background)
|
||||
}
|
||||
|
||||
func (s *agentDialog) Close() tea.Cmd {
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewAgentDialog(app *app.App) AgentDialog {
|
||||
dialog := &agentDialog{
|
||||
app: app,
|
||||
}
|
||||
|
||||
dialog.setupAllAgents()
|
||||
|
||||
dialog.modal = modal.New(
|
||||
modal.WithTitle("Select Agent"),
|
||||
modal.WithMaxWidth(dialog.dialogWidth+4),
|
||||
)
|
||||
|
||||
return dialog
|
||||
}
|
||||
@@ -99,7 +99,10 @@ func (c *completionDialogComponent) getAllCompletions(query string) tea.Cmd {
|
||||
baseStyle := styles.NewStyle().Background(t.BackgroundElement())
|
||||
|
||||
// Ensure stable provider order just in case
|
||||
sort.SliceStable(itemsByProvider, func(i, j int) bool { return itemsByProvider[i].idx < itemsByProvider[j].idx })
|
||||
sort.SliceStable(
|
||||
itemsByProvider,
|
||||
func(i, j int) bool { return itemsByProvider[i].idx < itemsByProvider[j].idx },
|
||||
)
|
||||
|
||||
final := make([]completions.CompletionSuggestion, 0)
|
||||
for _, entry := range itemsByProvider {
|
||||
@@ -167,6 +170,16 @@ func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
value := c.pseudoSearchTextArea.Value()
|
||||
width := lipgloss.Width(value)
|
||||
triggerWidth := lipgloss.Width(c.trigger)
|
||||
|
||||
if msg.String() == "space" || msg.String() == " " {
|
||||
item, i := c.list.GetSelectedItem()
|
||||
if i > -1 {
|
||||
return c, c.complete(item)
|
||||
}
|
||||
// If no exact match, close the dialog
|
||||
return c, c.close()
|
||||
}
|
||||
|
||||
// Only close on backspace when there are no characters left, unless we're back to just the trigger
|
||||
if (msg.String() != "backspace" && msg.String() != "ctrl+h") || (width <= triggerWidth && value != c.trigger) {
|
||||
return c, c.close()
|
||||
|
||||
@@ -173,7 +173,13 @@ func (c *listComponent[T]) moveUp() {
|
||||
}
|
||||
}
|
||||
|
||||
// If no selectable item found above, stay at current position
|
||||
// If no selectable item found above, wrap to the bottom
|
||||
for i := len(c.items) - 1; i > c.selectedIdx; i-- {
|
||||
if c.isSelectable(c.items[i]) {
|
||||
c.selectedIdx = i
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// moveDown moves the selection down, skipping non-selectable items
|
||||
@@ -183,20 +189,19 @@ func (c *listComponent[T]) moveDown() {
|
||||
}
|
||||
|
||||
originalIdx := c.selectedIdx
|
||||
for {
|
||||
if c.selectedIdx < len(c.items)-1 {
|
||||
c.selectedIdx++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if c.isSelectable(c.items[c.selectedIdx]) {
|
||||
// First try moving down from current position
|
||||
for i := c.selectedIdx + 1; i < len(c.items); i++ {
|
||||
if c.isSelectable(c.items[i]) {
|
||||
c.selectedIdx = i
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Prevent infinite loop
|
||||
if c.selectedIdx == originalIdx {
|
||||
break
|
||||
// If no selectable item found below, wrap to the top
|
||||
for i := 0; i < originalIdx; i++ {
|
||||
if c.isSelectable(c.items[i]) {
|
||||
c.selectedIdx = i
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,15 +138,18 @@ func TestCtrlNavigation(t *testing.T) {
|
||||
func TestNavigationBoundaries(t *testing.T) {
|
||||
list := createTestList()
|
||||
|
||||
// Test up arrow at first item (should stay at 0)
|
||||
// Test up arrow at first item (should wrap to last item)
|
||||
upKey := tea.KeyPressMsg{Code: tea.KeyUp}
|
||||
updatedModel, _ := list.Update(upKey)
|
||||
list = updatedModel.(*listComponent[testItem])
|
||||
_, idx := list.GetSelectedItem()
|
||||
if idx != 0 {
|
||||
t.Errorf("Expected to stay at index 0 when pressing up at first item, got %d", idx)
|
||||
if idx != 2 {
|
||||
t.Errorf("Expected to wrap to index 2 when pressing up at first item, got %d", idx)
|
||||
}
|
||||
|
||||
// Move to first item
|
||||
list.SetSelectedIndex(0)
|
||||
|
||||
// Move to last item
|
||||
downKey := tea.KeyPressMsg{Code: tea.KeyDown}
|
||||
updatedModel, _ = list.Update(downKey)
|
||||
@@ -158,12 +161,12 @@ func TestNavigationBoundaries(t *testing.T) {
|
||||
t.Errorf("Expected to be at index 2, got %d", idx)
|
||||
}
|
||||
|
||||
// Test down arrow at last item (should stay at 2)
|
||||
// Test down arrow at last item (should wrap to first item)
|
||||
updatedModel, _ = list.Update(downKey)
|
||||
list = updatedModel.(*listComponent[testItem])
|
||||
_, idx = list.GetSelectedItem()
|
||||
if idx != 2 {
|
||||
t.Errorf("Expected to stay at index 2 when pressing down at last item, got %d", idx)
|
||||
if idx != 0 {
|
||||
t.Errorf("Expected to wrap to index 0 when pressing down at last item, got %d", idx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,3 +211,39 @@ func TestEmptyList(t *testing.T) {
|
||||
t.Error("Expected IsEmpty() to return true for empty list")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapAroundNavigation(t *testing.T) {
|
||||
list := createTestList()
|
||||
|
||||
// Start at first item (index 0)
|
||||
_, idx := list.GetSelectedItem()
|
||||
if idx != 0 {
|
||||
t.Errorf("Expected to start at index 0, got %d", idx)
|
||||
}
|
||||
|
||||
// Press up arrow - should wrap to last item (index 2)
|
||||
upKey := tea.KeyPressMsg{Code: tea.KeyUp}
|
||||
updatedModel, _ := list.Update(upKey)
|
||||
list = updatedModel.(*listComponent[testItem])
|
||||
_, idx = list.GetSelectedItem()
|
||||
if idx != 2 {
|
||||
t.Errorf("Expected to wrap to index 2 when pressing up from first item, got %d", idx)
|
||||
}
|
||||
|
||||
// Press down arrow - should wrap to first item (index 0)
|
||||
downKey := tea.KeyPressMsg{Code: tea.KeyDown}
|
||||
updatedModel, _ = list.Update(downKey)
|
||||
list = updatedModel.(*listComponent[testItem])
|
||||
_, idx = list.GetSelectedItem()
|
||||
if idx != 0 {
|
||||
t.Errorf("Expected to wrap to index 0 when pressing down from last item, got %d", idx)
|
||||
}
|
||||
|
||||
// Navigate to middle and verify normal navigation still works
|
||||
updatedModel, _ = list.Update(downKey)
|
||||
list = updatedModel.(*listComponent[testItem])
|
||||
_, idx = list.GetSelectedItem()
|
||||
if idx != 1 {
|
||||
t.Errorf("Expected to move to index 1, got %d", idx)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,30 +121,14 @@ func (m *statusComponent) View() string {
|
||||
|
||||
var modeBackground compat.AdaptiveColor
|
||||
var modeForeground compat.AdaptiveColor
|
||||
switch m.app.AgentIndex {
|
||||
case 0:
|
||||
|
||||
agentColor := util.GetAgentColor(m.app.AgentIndex)
|
||||
|
||||
if m.app.AgentIndex == 0 {
|
||||
modeBackground = t.BackgroundElement()
|
||||
modeForeground = t.TextMuted()
|
||||
case 1:
|
||||
modeBackground = t.Secondary()
|
||||
modeForeground = t.BackgroundPanel()
|
||||
case 2:
|
||||
modeBackground = t.Accent()
|
||||
modeForeground = t.BackgroundPanel()
|
||||
case 3:
|
||||
modeBackground = t.Success()
|
||||
modeForeground = t.BackgroundPanel()
|
||||
case 4:
|
||||
modeBackground = t.Warning()
|
||||
modeForeground = t.BackgroundPanel()
|
||||
case 5:
|
||||
modeBackground = t.Primary()
|
||||
modeForeground = t.BackgroundPanel()
|
||||
case 6:
|
||||
modeBackground = t.Error()
|
||||
modeForeground = t.BackgroundPanel()
|
||||
default:
|
||||
modeBackground = t.Secondary()
|
||||
modeForeground = agentColor
|
||||
} else {
|
||||
modeBackground = agentColor
|
||||
modeForeground = t.BackgroundPanel()
|
||||
}
|
||||
|
||||
|
||||
@@ -420,6 +420,8 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch casted := p.(type) {
|
||||
case opencode.TextPart:
|
||||
return casted.ID == msg.Properties.Part.ID
|
||||
case opencode.ReasoningPart:
|
||||
return casted.ID == msg.Properties.Part.ID
|
||||
case opencode.FilePart:
|
||||
return casted.ID == msg.Properties.Part.ID
|
||||
case opencode.ToolPart:
|
||||
@@ -458,6 +460,8 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch casted := p.(type) {
|
||||
case opencode.TextPart:
|
||||
return casted.ID == msg.Properties.PartID
|
||||
case opencode.ReasoningPart:
|
||||
return casted.ID == msg.Properties.PartID
|
||||
case opencode.FilePart:
|
||||
return casted.ID == msg.Properties.PartID
|
||||
case opencode.ToolPart:
|
||||
@@ -592,6 +596,32 @@ func (a Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
}
|
||||
a.app.State.UpdateModelUsage(msg.Provider.ID, msg.Model.ID)
|
||||
cmds = append(cmds, a.app.SaveState())
|
||||
case app.AgentSelectedMsg:
|
||||
// Find the agent index
|
||||
for i, agent := range a.app.Agents {
|
||||
if agent.Name == msg.Agent.Name {
|
||||
a.app.AgentIndex = i
|
||||
break
|
||||
}
|
||||
}
|
||||
a.app.State.Agent = msg.Agent.Name
|
||||
|
||||
// Switch to the agent's preferred model if available
|
||||
if model, ok := a.app.State.AgentModel[msg.Agent.Name]; ok {
|
||||
for _, provider := range a.app.Providers {
|
||||
if provider.ID == model.ProviderID {
|
||||
a.app.Provider = &provider
|
||||
for _, m := range provider.Models {
|
||||
if m.ID == model.ModelID {
|
||||
a.app.Model = &m
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
cmds = append(cmds, a.app.SaveState())
|
||||
case dialog.ThemeSelectedMsg:
|
||||
a.app.State.Theme = msg.ThemeName
|
||||
cmds = append(cmds, a.app.SaveState())
|
||||
@@ -1109,9 +1139,24 @@ func (a Model) executeCommand(command commands.Command) (tea.Model, tea.Cmd) {
|
||||
}
|
||||
cmds = append(cmds, util.CmdHandler(chat.ToggleToolDetailsMsg{}))
|
||||
cmds = append(cmds, toast.NewInfoToast(message))
|
||||
case commands.ThinkingBlocksCommand:
|
||||
message := "Thinking blocks are now visible"
|
||||
if a.messages.ThinkingBlocksVisible() {
|
||||
message = "Thinking blocks are now hidden"
|
||||
}
|
||||
cmds = append(cmds, util.CmdHandler(chat.ToggleThinkingBlocksMsg{}))
|
||||
cmds = append(cmds, toast.NewInfoToast(message))
|
||||
case commands.ModelListCommand:
|
||||
modelDialog := dialog.NewModelDialog(a.app)
|
||||
a.modal = modelDialog
|
||||
case commands.AgentListCommand:
|
||||
agentDialog := dialog.NewAgentDialog(a.app)
|
||||
a.modal = agentDialog
|
||||
case commands.ModelCycleRecentCommand:
|
||||
slog.Debug("ModelCycleRecentCommand triggered")
|
||||
updated, cmd := a.app.CycleRecentModel()
|
||||
a.app = updated
|
||||
cmds = append(cmds, cmd)
|
||||
case commands.ThemeListCommand:
|
||||
themeDialog := dialog.NewThemeDialog()
|
||||
a.modal = themeDialog
|
||||
|
||||
@@ -3,6 +3,9 @@ package util
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/charmbracelet/lipgloss/v2/compat"
|
||||
"github.com/sst/opencode/internal/theme"
|
||||
)
|
||||
|
||||
var csiRE *regexp.Regexp
|
||||
@@ -89,5 +92,24 @@ func ConvertRGBToAnsi16Colors(s string) string {
|
||||
|
||||
// func looksLikeByte(tok string) bool {
|
||||
// v, err := strconv.Atoi(tok)
|
||||
// return err == nil && v >= 0 && v <= 255
|
||||
// return err == nil && v >= 0 && v <= 255
|
||||
// }
|
||||
|
||||
// GetAgentColor returns the color for a given agent index, matching the status bar colors
|
||||
func GetAgentColor(agentIndex int) compat.AdaptiveColor {
|
||||
t := theme.CurrentTheme()
|
||||
agentColors := []compat.AdaptiveColor{
|
||||
t.TextMuted(),
|
||||
t.Secondary(),
|
||||
t.Accent(),
|
||||
t.Success(),
|
||||
t.Warning(),
|
||||
t.Primary(),
|
||||
t.Error(),
|
||||
}
|
||||
|
||||
if agentIndex >= 0 && agentIndex < len(agentColors) {
|
||||
return agentColors[agentIndex]
|
||||
}
|
||||
return t.Secondary() // default fallback
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@opencode/web",
|
||||
"type": "module",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.22",
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"dev:remote": "sst shell --stage=dev --target=Web astro dev",
|
||||
@@ -11,7 +11,7 @@
|
||||
"astro": "astro"
|
||||
},
|
||||
"dependencies": {
|
||||
"@astrojs/cloudflare": "^12.5.4",
|
||||
"@astrojs/cloudflare": "12.6.3",
|
||||
"@astrojs/markdown-remark": "6.3.1",
|
||||
"@astrojs/solid-js": "5.1.0",
|
||||
"@astrojs/starlight": "0.34.3",
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { For, Show, onMount, Suspense, onCleanup, createMemo, createSignal, SuspenseList, createEffect } from "solid-js"
|
||||
import { DateTime } from "luxon"
|
||||
import { createStore, reconcile, unwrap } from "solid-js/store"
|
||||
import { mapValues } from "remeda"
|
||||
import { IconArrowDown } from "./icons"
|
||||
import { IconOpencode } from "./icons/custom"
|
||||
import styles from "./share.module.css"
|
||||
@@ -42,7 +41,6 @@ export default function Share(props: {
|
||||
id: string
|
||||
api: string
|
||||
info: Session.Info
|
||||
messages: Record<string, MessageWithParts>
|
||||
}) {
|
||||
let lastScrollY = 0
|
||||
let hasScrolledToAnchor = false
|
||||
@@ -50,7 +48,6 @@ export default function Share(props: {
|
||||
let scrollSentinel: HTMLElement | undefined
|
||||
let scrollObserver: IntersectionObserver | undefined
|
||||
|
||||
const id = props.id
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const debug = params.get("debug") === "true"
|
||||
|
||||
@@ -61,7 +58,17 @@ export default function Share(props: {
|
||||
const [store, setStore] = createStore<{
|
||||
info?: Session.Info
|
||||
messages: Record<string, MessageWithParts>
|
||||
}>({ info: props.info, messages: mapValues(props.messages, (x: any) => "metadata" in x ? fromV1(x) : x) })
|
||||
}>({
|
||||
info: {
|
||||
id: props.id,
|
||||
title: props.info.title,
|
||||
version: props.info.version,
|
||||
time: {
|
||||
created: props.info.time.created,
|
||||
updated: props.info.time.updated,
|
||||
},
|
||||
}, messages: {}
|
||||
})
|
||||
const messages = createMemo(() => Object.values(store.messages).toSorted((a, b) => a.id?.localeCompare(b.id)))
|
||||
const [connectionStatus, setConnectionStatus] = createSignal<[Status, string?]>(["disconnected", "Disconnected"])
|
||||
createEffect(() => {
|
||||
@@ -71,7 +78,7 @@ export default function Share(props: {
|
||||
onMount(() => {
|
||||
const apiUrl = props.api
|
||||
|
||||
if (!id) {
|
||||
if (!props.id) {
|
||||
setConnectionStatus(["error", "id not found"])
|
||||
return
|
||||
}
|
||||
@@ -96,7 +103,7 @@ export default function Share(props: {
|
||||
|
||||
// Always use secure WebSocket protocol (wss)
|
||||
const wsBaseUrl = apiUrl.replace(/^https?:\/\//, "wss://")
|
||||
const wsUrl = `${wsBaseUrl}/share_poll?id=${id}`
|
||||
const wsUrl = `${wsBaseUrl}/share_poll?id=${props.id}`
|
||||
console.log("Connecting to WebSocket URL:", wsUrl)
|
||||
|
||||
// Create WebSocket connection
|
||||
@@ -128,12 +135,10 @@ export default function Share(props: {
|
||||
setStore("messages", messageID, reconcile(d.content))
|
||||
}
|
||||
if (type === "part") {
|
||||
setStore("messages", d.content.messageID, "parts", arr => {
|
||||
setStore("messages", d.content.messageID, "parts", (arr) => {
|
||||
const index = arr.findIndex((x) => x.id === d.content.id)
|
||||
if (index === -1)
|
||||
arr.push(d.content)
|
||||
if (index > -1)
|
||||
arr[index] = d.content
|
||||
if (index === -1) arr.push(d.content)
|
||||
if (index > -1) arr[index] = d.content
|
||||
return [...arr]
|
||||
})
|
||||
}
|
||||
@@ -263,7 +268,9 @@ export default function Share(props: {
|
||||
},
|
||||
}
|
||||
|
||||
result.created = props.info.time.created
|
||||
if (!store.info) return result
|
||||
|
||||
result.created = store.info.time.created
|
||||
|
||||
const msgs = messages()
|
||||
for (let i = 0; i < msgs.length; i++) {
|
||||
@@ -292,197 +299,199 @@ export default function Share(props: {
|
||||
})
|
||||
|
||||
return (
|
||||
<main classList={{ [styles.root]: true, "not-content": true }}>
|
||||
<div data-component="header">
|
||||
<h1 data-component="header-title">{store.info?.title}</h1>
|
||||
<div data-component="header-details">
|
||||
<ul data-component="header-stats">
|
||||
<li title="opencode version" data-slot="item">
|
||||
<div data-slot="icon" title="opencode">
|
||||
<IconOpencode width={16} height={16} />
|
||||
</div>
|
||||
<Show when={store.info?.version} fallback="v0.0.1">
|
||||
<span>v{store.info?.version}</span>
|
||||
</Show>
|
||||
</li>
|
||||
{Object.values(data().models).length > 0 ? (
|
||||
<For each={Object.values(data().models)}>
|
||||
{([provider, model]) => (
|
||||
<li data-slot="item">
|
||||
<div data-slot="icon" title={provider}>
|
||||
<ProviderIcon model={model} />
|
||||
</div>
|
||||
<span data-slot="model">{model}</span>
|
||||
</li>
|
||||
)}
|
||||
</For>
|
||||
) : (
|
||||
<li>
|
||||
<span data-element-label>Models</span>
|
||||
<span data-placeholder>—</span>
|
||||
<Show when={store.info}>
|
||||
<main classList={{ [styles.root]: true, "not-content": true }}>
|
||||
<div data-component="header">
|
||||
<h1 data-component="header-title">{store.info?.title}</h1>
|
||||
<div data-component="header-details">
|
||||
<ul data-component="header-stats">
|
||||
<li title="opencode version" data-slot="item">
|
||||
<div data-slot="icon" title="opencode">
|
||||
<IconOpencode width={16} height={16} />
|
||||
</div>
|
||||
<Show when={store.info?.version} fallback="v0.0.1">
|
||||
<span>v{store.info?.version}</span>
|
||||
</Show>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
<div
|
||||
data-component="header-time"
|
||||
title={DateTime.fromMillis(data().created || 0).toLocaleString(DateTime.DATETIME_FULL_WITH_SECONDS)}
|
||||
>
|
||||
{DateTime.fromMillis(data().created || 0).toLocaleString(DateTime.DATETIME_MED)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Show when={data().messages.length > 0} fallback={<p>Waiting for messages...</p>}>
|
||||
<div class={styles.parts}>
|
||||
<SuspenseList revealOrder="forwards">
|
||||
<For each={data().messages}>
|
||||
{(msg, msgIndex) => {
|
||||
const filteredParts = createMemo(() =>
|
||||
msg.parts.filter((x, index) => {
|
||||
if (x.type === "step-start" && index > 0) return false
|
||||
if (x.type === "snapshot") return false
|
||||
if (x.type === "patch") return false
|
||||
if (x.type === "step-finish") return false
|
||||
if (x.type === "text" && x.synthetic === true) return false
|
||||
if (x.type === "tool" && x.tool === "todoread") return false
|
||||
if (x.type === "text" && !x.text) return false
|
||||
if (x.type === "tool" && (x.state.status === "pending" || x.state.status === "running"))
|
||||
return false
|
||||
return true
|
||||
})
|
||||
)
|
||||
|
||||
return (
|
||||
<Suspense>
|
||||
<For each={filteredParts()}>
|
||||
{(part, partIndex) => {
|
||||
const last = createMemo(
|
||||
() =>
|
||||
data().messages.length === msgIndex() + 1 && filteredParts().length === partIndex() + 1,
|
||||
)
|
||||
|
||||
onMount(() => {
|
||||
const hash = window.location.hash.slice(1)
|
||||
// Wait till all parts are loaded
|
||||
if (
|
||||
hash !== "" &&
|
||||
!hasScrolledToAnchor &&
|
||||
filteredParts().length === partIndex() + 1 &&
|
||||
data().messages.length === msgIndex() + 1
|
||||
) {
|
||||
hasScrolledToAnchor = true
|
||||
scrollToAnchor(hash)
|
||||
}
|
||||
})
|
||||
|
||||
return <Part last={last()} part={part} index={partIndex()} message={msg} />
|
||||
}}
|
||||
</For>
|
||||
</Suspense>
|
||||
)
|
||||
}}
|
||||
</For>
|
||||
</SuspenseList>
|
||||
<div data-section="part" data-part-type="summary">
|
||||
<div data-section="decoration">
|
||||
<span data-status={connectionStatus()[0]}></span>
|
||||
</div>
|
||||
<div data-section="content">
|
||||
<p data-section="copy">{getStatusText(connectionStatus())}</p>
|
||||
<ul data-section="stats">
|
||||
<li>
|
||||
<span data-element-label>Cost</span>
|
||||
{data().cost !== undefined ? (
|
||||
<span>${data().cost.toFixed(2)}</span>
|
||||
) : (
|
||||
<span data-placeholder>—</span>
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
<span data-element-label>Input Tokens</span>
|
||||
{data().tokens.input ? <span>{data().tokens.input}</span> : <span data-placeholder>—</span>}
|
||||
</li>
|
||||
<li>
|
||||
<span data-element-label>Output Tokens</span>
|
||||
{data().tokens.output ? <span>{data().tokens.output}</span> : <span data-placeholder>—</span>}
|
||||
</li>
|
||||
<li>
|
||||
<span data-element-label>Reasoning Tokens</span>
|
||||
{data().tokens.reasoning ? (
|
||||
<span>{data().tokens.reasoning}</span>
|
||||
) : (
|
||||
<span data-placeholder>—</span>
|
||||
)}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
|
||||
<Show when={debug}>
|
||||
<div style={{ margin: "2rem 0" }}>
|
||||
<div
|
||||
style={{
|
||||
border: "1px solid #ccc",
|
||||
padding: "1rem",
|
||||
"overflow-y": "auto",
|
||||
}}
|
||||
>
|
||||
<Show when={data().messages.length > 0} fallback={<p>Waiting for messages...</p>}>
|
||||
<ul style={{ "list-style-type": "none", padding: 0 }}>
|
||||
<For each={data().messages}>
|
||||
{(msg) => (
|
||||
<li
|
||||
style={{
|
||||
padding: "0.75rem",
|
||||
margin: "0.75rem 0",
|
||||
"box-shadow": "0 1px 3px rgba(0,0,0,0.1)",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<strong>Key:</strong> {msg.id}
|
||||
{Object.values(data().models).length > 0 ? (
|
||||
<For each={Object.values(data().models)}>
|
||||
{([provider, model]) => (
|
||||
<li data-slot="item">
|
||||
<div data-slot="icon" title={provider}>
|
||||
<ProviderIcon model={model} />
|
||||
</div>
|
||||
<pre>{JSON.stringify(msg, null, 2)}</pre>
|
||||
<span data-slot="model">{model}</span>
|
||||
</li>
|
||||
)}
|
||||
</For>
|
||||
</ul>
|
||||
</Show>
|
||||
) : (
|
||||
<li>
|
||||
<span data-element-label>Models</span>
|
||||
<span data-placeholder>—</span>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
<div
|
||||
data-component="header-time"
|
||||
title={DateTime.fromMillis(data().created || 0).toLocaleString(DateTime.DATETIME_FULL_WITH_SECONDS)}
|
||||
>
|
||||
{DateTime.fromMillis(data().created || 0).toLocaleString(DateTime.DATETIME_MED)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<Show when={showScrollButton()}>
|
||||
<button
|
||||
type="button"
|
||||
class={styles["scroll-button"]}
|
||||
onClick={() => document.body.scrollIntoView({ behavior: "smooth", block: "end" })}
|
||||
onMouseEnter={() => {
|
||||
setIsButtonHovered(true)
|
||||
if (scrollTimeout) {
|
||||
clearTimeout(scrollTimeout)
|
||||
}
|
||||
}}
|
||||
onMouseLeave={() => {
|
||||
setIsButtonHovered(false)
|
||||
if (showScrollButton()) {
|
||||
scrollTimeout = window.setTimeout(() => {
|
||||
if (!isButtonHovered()) {
|
||||
setShowScrollButton(false)
|
||||
}
|
||||
}, 3000)
|
||||
}
|
||||
}}
|
||||
title="Scroll to bottom"
|
||||
aria-label="Scroll to bottom"
|
||||
>
|
||||
<IconArrowDown width={20} height={20} />
|
||||
</button>
|
||||
</Show>
|
||||
</main>
|
||||
<div>
|
||||
<Show when={data().messages.length > 0} fallback={<p>Waiting for messages...</p>}>
|
||||
<div class={styles.parts}>
|
||||
<SuspenseList revealOrder="forwards">
|
||||
<For each={data().messages}>
|
||||
{(msg, msgIndex) => {
|
||||
const filteredParts = createMemo(() =>
|
||||
msg.parts.filter((x, index) => {
|
||||
if (x.type === "step-start" && index > 0) return false
|
||||
if (x.type === "snapshot") return false
|
||||
if (x.type === "patch") return false
|
||||
if (x.type === "step-finish") return false
|
||||
if (x.type === "text" && x.synthetic === true) return false
|
||||
if (x.type === "tool" && x.tool === "todoread") return false
|
||||
if (x.type === "text" && !x.text) return false
|
||||
if (x.type === "tool" && (x.state.status === "pending" || x.state.status === "running"))
|
||||
return false
|
||||
return true
|
||||
}),
|
||||
)
|
||||
|
||||
return (
|
||||
<Suspense>
|
||||
<For each={filteredParts()}>
|
||||
{(part, partIndex) => {
|
||||
const last = createMemo(
|
||||
() =>
|
||||
data().messages.length === msgIndex() + 1 && filteredParts().length === partIndex() + 1,
|
||||
)
|
||||
|
||||
onMount(() => {
|
||||
const hash = window.location.hash.slice(1)
|
||||
// Wait till all parts are loaded
|
||||
if (
|
||||
hash !== "" &&
|
||||
!hasScrolledToAnchor &&
|
||||
filteredParts().length === partIndex() + 1 &&
|
||||
data().messages.length === msgIndex() + 1
|
||||
) {
|
||||
hasScrolledToAnchor = true
|
||||
scrollToAnchor(hash)
|
||||
}
|
||||
})
|
||||
|
||||
return <Part last={last()} part={part} index={partIndex()} message={msg} />
|
||||
}}
|
||||
</For>
|
||||
</Suspense>
|
||||
)
|
||||
}}
|
||||
</For>
|
||||
</SuspenseList>
|
||||
<div data-section="part" data-part-type="summary">
|
||||
<div data-section="decoration">
|
||||
<span data-status={connectionStatus()[0]}></span>
|
||||
</div>
|
||||
<div data-section="content">
|
||||
<p data-section="copy">{getStatusText(connectionStatus())}</p>
|
||||
<ul data-section="stats">
|
||||
<li>
|
||||
<span data-element-label>Cost</span>
|
||||
{data().cost !== undefined ? (
|
||||
<span>${data().cost.toFixed(2)}</span>
|
||||
) : (
|
||||
<span data-placeholder>—</span>
|
||||
)}
|
||||
</li>
|
||||
<li>
|
||||
<span data-element-label>Input Tokens</span>
|
||||
{data().tokens.input ? <span>{data().tokens.input}</span> : <span data-placeholder>—</span>}
|
||||
</li>
|
||||
<li>
|
||||
<span data-element-label>Output Tokens</span>
|
||||
{data().tokens.output ? <span>{data().tokens.output}</span> : <span data-placeholder>—</span>}
|
||||
</li>
|
||||
<li>
|
||||
<span data-element-label>Reasoning Tokens</span>
|
||||
{data().tokens.reasoning ? (
|
||||
<span>{data().tokens.reasoning}</span>
|
||||
) : (
|
||||
<span data-placeholder>—</span>
|
||||
)}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
|
||||
<Show when={debug}>
|
||||
<div style={{ margin: "2rem 0" }}>
|
||||
<div
|
||||
style={{
|
||||
border: "1px solid #ccc",
|
||||
padding: "1rem",
|
||||
"overflow-y": "auto",
|
||||
}}
|
||||
>
|
||||
<Show when={data().messages.length > 0} fallback={<p>Waiting for messages...</p>}>
|
||||
<ul style={{ "list-style-type": "none", padding: 0 }}>
|
||||
<For each={data().messages}>
|
||||
{(msg) => (
|
||||
<li
|
||||
style={{
|
||||
padding: "0.75rem",
|
||||
margin: "0.75rem 0",
|
||||
"box-shadow": "0 1px 3px rgba(0,0,0,0.1)",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<strong>Key:</strong> {msg.id}
|
||||
</div>
|
||||
<pre>{JSON.stringify(msg, null, 2)}</pre>
|
||||
</li>
|
||||
)}
|
||||
</For>
|
||||
</ul>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<Show when={showScrollButton()}>
|
||||
<button
|
||||
type="button"
|
||||
class={styles["scroll-button"]}
|
||||
onClick={() => document.body.scrollIntoView({ behavior: "smooth", block: "end" })}
|
||||
onMouseEnter={() => {
|
||||
setIsButtonHovered(true)
|
||||
if (scrollTimeout) {
|
||||
clearTimeout(scrollTimeout)
|
||||
}
|
||||
}}
|
||||
onMouseLeave={() => {
|
||||
setIsButtonHovered(false)
|
||||
if (showScrollButton()) {
|
||||
scrollTimeout = window.setTimeout(() => {
|
||||
if (!isButtonHovered()) {
|
||||
setShowScrollButton(false)
|
||||
}
|
||||
}, 3000)
|
||||
}
|
||||
}}
|
||||
title="Scroll to bottom"
|
||||
aria-label="Scroll to bottom"
|
||||
>
|
||||
<IconArrowDown width={20} height={20} />
|
||||
</button>
|
||||
</Show>
|
||||
</main>
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -510,6 +519,7 @@ export function fromV1(v1: Message.Info): MessageWithParts {
|
||||
},
|
||||
modelID: v1.metadata.assistant!.modelID,
|
||||
providerID: v1.metadata.assistant!.providerID,
|
||||
mode: "build",
|
||||
system: v1.metadata.assistant!.system,
|
||||
error: v1.metadata.error,
|
||||
parts: v1.parts.flatMap((part, index): MessageV2.Part[] => {
|
||||
|
||||
@@ -54,7 +54,10 @@ export function IconOpencode(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||
export function IconMeta(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||
<path fill="currentColor" d="M16.92 4.5c-1.851 0-3.298 1.394-4.608 3.165C10.512 5.373 9.007 4.5 7.206 4.5C3.534 4.5.72 9.28.72 14.338c0 3.165 1.531 5.162 4.096 5.162c1.846 0 3.174-.87 5.535-4.997c0 0 .984-1.737 1.66-2.934q.356.574.75 1.238l1.107 1.862c2.156 3.608 3.358 4.831 5.534 4.831c2.5 0 3.89-2.024 3.89-5.255c0-5.297-2.877-9.745-6.372-9.745m-8.37 8.886c-1.913 3-2.575 3.673-3.64 3.673c-1.097 0-1.749-.963-1.749-2.68c0-3.672 1.831-7.427 4.014-7.427c1.182 0 2.17.682 3.683 2.848c-1.437 2.204-2.307 3.586-2.307 3.586m7.224-.377L14.45 10.8a45 45 0 0 0-1.032-1.608c1.193-1.841 2.176-2.759 3.347-2.759c2.43 0 4.375 3.58 4.375 7.976c0 1.676-.549 2.649-1.686 2.649c-1.09 0-1.61-.72-3.68-4.05" />
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M16.92 4.5c-1.851 0-3.298 1.394-4.608 3.165C10.512 5.373 9.007 4.5 7.206 4.5C3.534 4.5.72 9.28.72 14.338c0 3.165 1.531 5.162 4.096 5.162c1.846 0 3.174-.87 5.535-4.997c0 0 .984-1.737 1.66-2.934q.356.574.75 1.238l1.107 1.862c2.156 3.608 3.358 4.831 5.534 4.831c2.5 0 3.89-2.024 3.89-5.255c0-5.297-2.877-9.745-6.372-9.745m-8.37 8.886c-1.913 3-2.575 3.673-3.64 3.673c-1.097 0-1.749-.963-1.749-2.68c0-3.672 1.831-7.427 4.014-7.427c1.182 0 2.17.682 3.683 2.848c-1.437 2.204-2.307 3.586-2.307 3.586m7.224-.377L14.45 10.8a45 45 0 0 0-1.032-1.608c1.193-1.841 2.176-2.759 3.347-2.759c2.43 0 4.375 3.58 4.375 7.976c0 1.676-.549 2.649-1.686 2.649c-1.09 0-1.61-.72-3.68-4.05"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -63,6 +66,22 @@ export function IconMeta(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||
export function IconRobot(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||
<path fill="currentColor" d="M13.5 2c0 .444-.193.843-.5 1.118V5h5a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3h5V3.118A1.5 1.5 0 1 1 13.5 2M6 7a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8a1 1 0 0 0-1-1zm-4 3H0v6h2zm20 0h2v6h-2zM9 14.5a1.5 1.5 0 1 0 0-3a1.5 1.5 0 0 0 0 3m6 0a1.5 1.5 0 1 0 0-3a1.5 1.5 0 0 0 0 3" /></svg>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M13.5 2c0 .444-.193.843-.5 1.118V5h5a3 3 0 0 1 3 3v10a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3h5V3.118A1.5 1.5 0 1 1 13.5 2M6 7a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8a1 1 0 0 0-1-1zm-4 3H0v6h2zm20 0h2v6h-2zM9 14.5a1.5 1.5 0 1 0 0-3a1.5 1.5 0 0 0 0 3m6 0a1.5 1.5 0 1 0 0-3a1.5 1.5 0 0 0 0 3"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
// https://icones.js.org/collection/ri?s=brain&icon=ri:brain-2-line
|
||||
export function IconBrain(props: JSX.SvgSVGAttributes<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M7 6q.001.357.115.67a1 1 0 0 1-1 1.333L6 8a2 2 0 0 0-1.491 3.333a1 1 0 0 1 0 1.334a2 2 0 0 0 .864 3.233a1 1 0 0 1 .67 1.135a2.5 2.5 0 1 0 4.932.824q.009-.063.025-.123V6a2 2 0 1 0-4 0m6 11.736q.016.06.025.122a2.5 2.5 0 1 0 4.932-.823a1 1 0 0 1 .67-1.135a2 2 0 0 0 .864-3.233a1 1 0 0 1 0-1.334a2 2 0 0 0-1.607-3.33a1 1 0 0 1-.999-1.333q.113-.313.115-.67a2 2 0 1 0-4 0zM9 2a4 4 0 0 1 3 1.354a4 4 0 0 1 6.998 2.771A4.002 4.002 0 0 1 21.465 12A3.997 3.997 0 0 1 20 17.465v.035a4.5 4.5 0 0 1-8 2.828A4.5 4.5 0 0 1 4 17.5v-.035A3.997 3.997 0 0 1 2.535 12a4.002 4.002 0 0 1 2.467-5.874L5 6a4 4 0 0 1 4-4"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -128,6 +128,29 @@
|
||||
max-width: var(--md-tool-width);
|
||||
}
|
||||
|
||||
[data-component="assistant-reasoning"] {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
flex-grow: 1;
|
||||
max-width: var(--md-tool-width);
|
||||
|
||||
[data-component="assistant-reasoning-markdown"] {
|
||||
align-self: flex-start;
|
||||
font-size: 0.75rem;
|
||||
border: 1px solid var(--sl-color-blue-high);
|
||||
padding: 0.5rem calc(0.5rem + 3px);
|
||||
border-radius: 0.25rem;
|
||||
position: relative;
|
||||
|
||||
[data-component="copy-button"] {
|
||||
top: 0.5rem;
|
||||
right: calc(0.5rem - 1px);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[data-component="assistant-text"] {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
IconMagnifyingGlass,
|
||||
IconDocumentMagnifyingGlass,
|
||||
} from "../icons"
|
||||
import { IconMeta, IconRobot, IconOpenAI, IconGemini, IconAnthropic } from "../icons/custom"
|
||||
import { IconMeta, IconRobot, IconOpenAI, IconGemini, IconAnthropic, IconBrain } from "../icons/custom"
|
||||
import { ContentCode } from "./content-code"
|
||||
import { ContentDiff } from "./content-diff"
|
||||
import { ContentText } from "./content-text"
|
||||
@@ -83,6 +83,9 @@ export function Part(props: PartProps) {
|
||||
>
|
||||
{(model) => <ProviderIcon model={model()} size={18} />}
|
||||
</Match>
|
||||
<Match when={props.part.type === "reasoning" && props.message.role === "assistant"}>
|
||||
<IconBrain width={18} height={18} />
|
||||
</Match>
|
||||
<Match when={props.part.type === "tool" && props.part.tool === "todowrite"}>
|
||||
<IconQueueList width={18} height={18} />
|
||||
</Match>
|
||||
@@ -149,25 +152,48 @@ export function Part(props: PartProps) {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{props.message.role === "user" && props.part.type === "file" && (
|
||||
<div data-component="attachment">
|
||||
<div data-slot="copy">Attachment</div>
|
||||
<div data-slot="filename">{props.part.filename}</div>
|
||||
{props.message.role === "assistant" && props.part.type === "reasoning" && (
|
||||
<div data-component="tool">
|
||||
<div data-component="tool-title">
|
||||
<span data-slot="name">Thinking</span>
|
||||
</div>
|
||||
<Show when={props.part.text}>
|
||||
<div data-component="assistant-reasoning">
|
||||
<ResultsButton showCopy="Show details" hideCopy="Hide details">
|
||||
<div data-component="assistant-reasoning-markdown">
|
||||
<ContentMarkdown expand text={props.part.text || "Thinking..."} />
|
||||
</div>
|
||||
</ResultsButton>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
)}
|
||||
{props.part.type === "step-start" && props.message.role === "assistant" && (
|
||||
<div data-component="step-start">
|
||||
<div data-slot="provider">{props.message.providerID}</div>
|
||||
<div data-slot="model">{props.message.modelID}</div>
|
||||
</div>
|
||||
)}
|
||||
{props.part.type === "tool" && props.part.state.status === "error" && (
|
||||
<div data-component="tool" data-tool="error">
|
||||
<ContentError>{formatErrorString(props.part.state.error)}</ContentError>
|
||||
<Spacer />
|
||||
</div>
|
||||
)}
|
||||
{props.part.type === "tool" &&
|
||||
{
|
||||
props.message.role === "user" && props.part.type === "file" && (
|
||||
<div data-component="attachment">
|
||||
<div data-slot="copy">Attachment</div>
|
||||
<div data-slot="filename">{props.part.filename}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
props.part.type === "step-start" && props.message.role === "assistant" && (
|
||||
<div data-component="step-start">
|
||||
<div data-slot="provider">{props.message.providerID}</div>
|
||||
<div data-slot="model">{props.message.modelID}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
props.part.type === "tool" && props.part.state.status === "error" && (
|
||||
<div data-component="tool" data-tool="error">
|
||||
<ContentError>{formatErrorString(props.part.state.error)}</ContentError>
|
||||
<Spacer />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
{
|
||||
props.part.type === "tool" &&
|
||||
props.part.state.status === "completed" &&
|
||||
props.message.role === "assistant" && (
|
||||
<>
|
||||
@@ -269,9 +295,10 @@ export function Part(props: PartProps) {
|
||||
.toMillis()}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div >
|
||||
</div >
|
||||
)
|
||||
}
|
||||
|
||||
@@ -577,7 +604,7 @@ export function BashTool(props: ToolProps) {
|
||||
return (
|
||||
<ContentBash
|
||||
command={props.state.input.command}
|
||||
output={props.state.metadata?.stdout || ""}
|
||||
output={props.state.metadata.output ?? props.state.metadata?.stdout}
|
||||
description={props.state.metadata.description}
|
||||
/>
|
||||
)
|
||||
@@ -653,9 +680,7 @@ function TaskTool(props: ToolProps) {
|
||||
<span data-slot="name">Task</span>
|
||||
<span data-slot="target">{props.state.input.description}</span>
|
||||
</div>
|
||||
<div data-component="tool-input">
|
||||
“{props.state.input.prompt}”
|
||||
</div>
|
||||
<div data-component="tool-input">“{props.state.input.prompt}”</div>
|
||||
<ResultsButton showCopy="Show output" hideCopy="Hide output">
|
||||
<div data-component="tool-output">
|
||||
<ContentMarkdown expand text={props.state.output} />
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: Agents
|
||||
description: Configure and use specialized agents in opencode.
|
||||
description: Configure and use specialized agents.
|
||||
---
|
||||
|
||||
Agents are specialized AI assistants that can be configured for specific tasks and workflows. They allow you to create focused tools with custom prompts, models, and tool access.
|
||||
@@ -360,6 +360,29 @@ The `mode` option can be set to `primary`, `subagent`, or `all`. If no `mode` is
|
||||
|
||||
---
|
||||
|
||||
### Additional
|
||||
|
||||
Any other options you specify in your agent configuration will be **passed through directly** to the provider as model options. This allows you to use provider-specific features and parameters.
|
||||
|
||||
For example, with OpenAI's reasoning models, you can control the reasoning effort:
|
||||
|
||||
```json title="opencode.json" {6,7}
|
||||
{
|
||||
"agent": {
|
||||
"deep-thinker": {
|
||||
"description": "Agent that uses high reasoning effort for complex problems",
|
||||
"model": "openai/gpt-5-turbo",
|
||||
"reasoningEffort": "high",
|
||||
"textVerbosity": "low"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
These additional options are model and provider-specific. Check your provider's documentation for available parameters.
|
||||
|
||||
---
|
||||
|
||||
## Create agents
|
||||
|
||||
You can create new agents using the following command:
|
||||
|
||||
@@ -71,25 +71,6 @@ Your editor should be able to validate and autocomplete based on the schema.
|
||||
|
||||
---
|
||||
|
||||
### Modes
|
||||
|
||||
opencode comes with two built-in modes: _build_, the default with all tools enabled. And _plan_, restricted mode with file modification tools disabled. You can override these built-in modes or define your own custom modes with the `mode` option.
|
||||
|
||||
```json title="opencode.json"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"mode": {
|
||||
"build": {},
|
||||
"plan": {},
|
||||
"my-custom-mode": {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
[Learn more here](/docs/modes).
|
||||
|
||||
---
|
||||
|
||||
### Models
|
||||
|
||||
You can configure the providers and models you want to use in your opencode config through the `provider`, `model` and `small_model` options.
|
||||
@@ -337,7 +318,7 @@ Use `{file:path/to/file}` to substitute the contents of a file:
|
||||
```json title="opencode.json"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"instructions": ["{file:./custom-instructions.md}"],
|
||||
"instructions": ["./custom-instructions.md"],
|
||||
"provider": {
|
||||
"openai": {
|
||||
"options": {
|
||||
|
||||
@@ -16,7 +16,7 @@ opencode comes with several built-in formatters for popular languages and framew
|
||||
| gofmt | .go | `gofmt` command available |
|
||||
| mix | .ex, .exs, .eex, .heex, .leex, .neex, .sface | `mix` command available |
|
||||
| prettier | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://prettier.io/docs/en/index.html) | `prettier` dependency in `package.json` |
|
||||
| biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://biomejs.dev/) | `biome.json` config file |
|
||||
| biome | .js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and [more](https://biomejs.dev/) | `biome.json(c)` config file |
|
||||
| zig | .zig, .zon | `zig` command available |
|
||||
| clang-format | .c, .cpp, .h, .hpp, .ino, and [more](https://clang.llvm.org/docs/ClangFormat.html) | `.clang-format` config file |
|
||||
| ktlint | .kt, .kts | `ktlint` command available |
|
||||
|
||||
@@ -11,9 +11,10 @@ opencode integrates with your Language Server Protocol (LSP) to help the LLM int
|
||||
|
||||
opencode comes with several built-in LSP servers for popular languages:
|
||||
|
||||
| LSP Server | Extensions | Requirements |
|
||||
| LSP Server | Extensions | Requirements |
|
||||
| ---------- | -------------------------------------------- | ----------------------------------- |
|
||||
| typescript | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `typescript` dependency in project |
|
||||
| eslint | .ts, .tsx, .js, .jsx, .mjs, .cjs, .mts, .cts | `eslint` dependency in project |
|
||||
| gopls | .go | `go` command available |
|
||||
| ruby-lsp | .rb, .rake, .gemspec, .ru | `ruby` and `gem` commands available |
|
||||
| pyright | .py, .pyi | `pyright` dependency installed |
|
||||
@@ -41,7 +42,7 @@ You can customize LSP servers through the `lsp` section in your opencode config.
|
||||
```json title="opencode.json"
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"lsp": { }
|
||||
"lsp": {}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -49,7 +50,7 @@ Each LSP server supports the following:
|
||||
|
||||
| Property | Type | Description |
|
||||
| ---------------- | -------- | ------------------------------------------------- |
|
||||
| `disabled` | boolean | Set this to `true` to disable the LSP server |
|
||||
| `disabled` | boolean | Set this to `true` to disable the LSP server |
|
||||
| `command` | string[] | The command to start the LSP server |
|
||||
| `extensions` | string[] | File extensions this LSP server should handle |
|
||||
| `env` | object | Environment variables to set when starting server |
|
||||
|
||||
@@ -13,6 +13,14 @@ The permissions system provides granular control to restrict what actions AI age
|
||||
|
||||
Permissions are configured in your `opencode.json` file under the `permission` key. Here are the available options.
|
||||
|
||||
### Tool Permission Support
|
||||
|
||||
| Tool | Description |
|
||||
| ---------- | ------------------------------- |
|
||||
| `edit` | Control file editing operations |
|
||||
| `bash` | Control bash command execution |
|
||||
| `webfetch` | Control web content fetching |
|
||||
|
||||
---
|
||||
|
||||
### edit
|
||||
|
||||
@@ -90,7 +90,7 @@ We are using `osascript` to run AppleScript on macOS. Here we are using it to se
|
||||
|
||||
Prevent opencode from reading `.env` files:
|
||||
|
||||
```javascript title=".opencode/plugin/slack.js"
|
||||
```javascript title=".opencode/plugin/env-protection.js"
|
||||
export const EnvProtection = async ({ client, $ }) => {
|
||||
return {
|
||||
tool: {
|
||||
|
||||
@@ -546,7 +546,7 @@ To use Kimi K2 from Moonshot AI:
|
||||
|
||||
1. Head over to the [Moonshot AI console](https://platform.moonshot.ai/console), create an account, and click **Create API key**.
|
||||
|
||||
2. Run `opencode auth login` and select **Other**.
|
||||
2. Run `opencode auth login` and select **Moonshot AI**.
|
||||
|
||||
```bash
|
||||
$ opencode auth login
|
||||
@@ -555,11 +555,11 @@ To use Kimi K2 from Moonshot AI:
|
||||
│
|
||||
◆ Select provider
|
||||
│ ...
|
||||
│ ● Other
|
||||
│ ● Moonshot AI
|
||||
└
|
||||
```
|
||||
|
||||
3. Enter `moonshot` as the provider ID.
|
||||
3. Enter your Moonshot API key.
|
||||
|
||||
```bash
|
||||
$ opencode auth login
|
||||
@@ -567,48 +567,14 @@ To use Kimi K2 from Moonshot AI:
|
||||
┌ Add credential
|
||||
│
|
||||
◇ Select provider
|
||||
│ Other
|
||||
│
|
||||
◇ Enter provider id
|
||||
│ moonshot
|
||||
└
|
||||
```
|
||||
|
||||
4. Enter your Moonshot API key.
|
||||
|
||||
```bash
|
||||
$ opencode auth login
|
||||
|
||||
┌ Add credential
|
||||
│ Moonshot AI
|
||||
│
|
||||
◇ Enter your API key
|
||||
│ sk-...
|
||||
│ _
|
||||
└
|
||||
```
|
||||
|
||||
5. Configure Moonshot in your opencode config.
|
||||
|
||||
```json title="opencode.json" ""moonshot"" {5-15}
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"provider": {
|
||||
"moonshot": {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": "Moonshot AI",
|
||||
"options": {
|
||||
"baseURL": "https://api.moonshot.ai/v1"
|
||||
},
|
||||
"models": {
|
||||
"kimi-k2-0711-preview": {
|
||||
"name": "Kimi K2"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
6. Run the `/models` command to select _Kimi K2_.
|
||||
4. Run the `/models` command to select _Kimi K2_.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
---
|
||||
import { Base64 } from "js-base64";
|
||||
import config from "virtual:starlight/user-config";
|
||||
|
||||
import config from '../../../config.mjs'
|
||||
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
|
||||
|
||||
+39
-1
@@ -38,10 +38,48 @@ await import(`../packages/sdk/js/script/publish.ts`)
|
||||
console.log("\n=== plugin ===\n")
|
||||
await import(`../packages/plugin/script/publish.ts`)
|
||||
|
||||
const dir = new URL("..", import.meta.url).pathname
|
||||
process.chdir(dir)
|
||||
|
||||
if (!snapshot) {
|
||||
await $`git commit -am "release: v${version}"`
|
||||
await $`git tag v${version}`
|
||||
await $`git push origin HEAD --tags --no-verify`
|
||||
await $`git fetch origin`
|
||||
await $`git cherry-pick HEAD..origin/dev`.nothrow()
|
||||
await $`git push origin HEAD --tags --no-verify --force`
|
||||
|
||||
const previous = await fetch("https://api.github.com/repos/sst/opencode/releases/latest")
|
||||
.then((res) => {
|
||||
if (!res.ok) throw new Error(res.statusText)
|
||||
return res.json()
|
||||
})
|
||||
.then((data) => data.tag_name)
|
||||
|
||||
console.log("finding commits between", previous, "and", "HEAD")
|
||||
const commits = await fetch(`https://api.github.com/repos/sst/opencode/compare/${previous}...HEAD`)
|
||||
.then((res) => res.json())
|
||||
.then((data) => data.commits || [])
|
||||
|
||||
const raw = commits.map((commit: any) => `- ${commit.commit.message.split("\n").join(" ")}`)
|
||||
console.log(raw)
|
||||
|
||||
const notes =
|
||||
raw
|
||||
.filter((x: string) => {
|
||||
const lower = x.toLowerCase()
|
||||
return (
|
||||
!lower.includes("release:") &&
|
||||
!lower.includes("ignore:") &&
|
||||
!lower.includes("chore:") &&
|
||||
!lower.includes("ci:") &&
|
||||
!lower.includes("wip:") &&
|
||||
!lower.includes("docs:") &&
|
||||
!lower.includes("doc:")
|
||||
)
|
||||
})
|
||||
.join("\n") || "No notable changes"
|
||||
|
||||
await $`gh release create v${version} --title "v${version}" --notes ${notes} ./packages/opencode/dist/*.zip`
|
||||
}
|
||||
if (snapshot) {
|
||||
await $`git checkout -b snapshot-${version}`
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "opencode",
|
||||
"displayName": "opencode",
|
||||
"description": "opencode for VS Code",
|
||||
"version": "0.4.1",
|
||||
"version": "0.4.22",
|
||||
"publisher": "sst-dev",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
Vendored
+4
@@ -63,6 +63,10 @@ declare module "sst" {
|
||||
"type": "sst.sst.Secret"
|
||||
"value": string
|
||||
}
|
||||
"GOOGLE_CLIENT_ID": {
|
||||
"type": "sst.sst.Secret"
|
||||
"value": string
|
||||
}
|
||||
"GatewayApi": {
|
||||
"type": "sst.cloudflare.Worker"
|
||||
"url": string
|
||||
|
||||
Reference in New Issue
Block a user