mirror of
https://github.com/anomalyco/opencode.git
synced 2026-02-19 23:34:32 +00:00
Compare commits
1 Commits
dev
...
snapshot-n
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c501b1583 |
38
bun.lock
38
bun.lock
@@ -25,7 +25,7 @@
|
||||
},
|
||||
"packages/app": {
|
||||
"name": "@opencode-ai/app",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@kobalte/core": "catalog:",
|
||||
"@opencode-ai/sdk": "workspace:*",
|
||||
@@ -75,7 +75,7 @@
|
||||
},
|
||||
"packages/console/app": {
|
||||
"name": "@opencode-ai/console-app",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@cloudflare/vite-plugin": "1.15.2",
|
||||
"@ibm/plex": "6.4.1",
|
||||
@@ -109,7 +109,7 @@
|
||||
},
|
||||
"packages/console/core": {
|
||||
"name": "@opencode-ai/console-core",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-sts": "3.782.0",
|
||||
"@jsx-email/render": "1.1.1",
|
||||
@@ -136,7 +136,7 @@
|
||||
},
|
||||
"packages/console/function": {
|
||||
"name": "@opencode-ai/console-function",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@ai-sdk/anthropic": "2.0.0",
|
||||
"@ai-sdk/openai": "2.0.2",
|
||||
@@ -160,7 +160,7 @@
|
||||
},
|
||||
"packages/console/mail": {
|
||||
"name": "@opencode-ai/console-mail",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@jsx-email/all": "2.2.3",
|
||||
"@jsx-email/cli": "1.4.3",
|
||||
@@ -184,7 +184,7 @@
|
||||
},
|
||||
"packages/desktop": {
|
||||
"name": "@opencode-ai/desktop",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@opencode-ai/app": "workspace:*",
|
||||
"@opencode-ai/ui": "workspace:*",
|
||||
@@ -217,7 +217,7 @@
|
||||
},
|
||||
"packages/enterprise": {
|
||||
"name": "@opencode-ai/enterprise",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@opencode-ai/ui": "workspace:*",
|
||||
"@opencode-ai/util": "workspace:*",
|
||||
@@ -246,7 +246,7 @@
|
||||
},
|
||||
"packages/function": {
|
||||
"name": "@opencode-ai/function",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@octokit/auth-app": "8.0.1",
|
||||
"@octokit/rest": "catalog:",
|
||||
@@ -262,7 +262,7 @@
|
||||
},
|
||||
"packages/opencode": {
|
||||
"name": "opencode",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"bin": {
|
||||
"opencode": "./bin/opencode",
|
||||
},
|
||||
@@ -315,7 +315,6 @@
|
||||
"ai": "catalog:",
|
||||
"ai-gateway-provider": "2.3.1",
|
||||
"bonjour-service": "1.3.0",
|
||||
"bun-pty": "0.4.8",
|
||||
"chokidar": "4.0.3",
|
||||
"clipboardy": "4.0.0",
|
||||
"decimal.js": "10.5.0",
|
||||
@@ -331,6 +330,7 @@
|
||||
"jsonc-parser": "3.3.1",
|
||||
"mime-types": "3.0.2",
|
||||
"minimatch": "10.0.3",
|
||||
"node-pty": "1.0.0",
|
||||
"open": "10.1.2",
|
||||
"opentui-spinner": "0.0.6",
|
||||
"partial-json": "0.1.7",
|
||||
@@ -376,7 +376,7 @@
|
||||
},
|
||||
"packages/plugin": {
|
||||
"name": "@opencode-ai/plugin",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@opencode-ai/sdk": "workspace:*",
|
||||
"zod": "catalog:",
|
||||
@@ -396,7 +396,7 @@
|
||||
},
|
||||
"packages/sdk/js": {
|
||||
"name": "@opencode-ai/sdk",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"devDependencies": {
|
||||
"@hey-api/openapi-ts": "0.90.10",
|
||||
"@tsconfig/node22": "catalog:",
|
||||
@@ -407,7 +407,7 @@
|
||||
},
|
||||
"packages/slack": {
|
||||
"name": "@opencode-ai/slack",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@opencode-ai/sdk": "workspace:*",
|
||||
"@slack/bolt": "^3.17.1",
|
||||
@@ -420,7 +420,7 @@
|
||||
},
|
||||
"packages/ui": {
|
||||
"name": "@opencode-ai/ui",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@kobalte/core": "catalog:",
|
||||
"@opencode-ai/sdk": "workspace:*",
|
||||
@@ -462,7 +462,7 @@
|
||||
},
|
||||
"packages/util": {
|
||||
"name": "@opencode-ai/util",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"zod": "catalog:",
|
||||
},
|
||||
@@ -473,7 +473,7 @@
|
||||
},
|
||||
"packages/web": {
|
||||
"name": "@opencode-ai/web",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@astrojs/cloudflare": "12.6.3",
|
||||
"@astrojs/markdown-remark": "6.3.1",
|
||||
@@ -2222,8 +2222,6 @@
|
||||
|
||||
"bun-ffi-structs": ["bun-ffi-structs@0.1.2", "", { "peerDependencies": { "typescript": "^5" } }, "sha512-Lh1oQAYHDcnesJauieA4UNkWGXY9hYck7OA5IaRwE3Bp6K2F2pJSNYqq+hIy7P3uOvo3km3oxS8304g5gDMl/w=="],
|
||||
|
||||
"bun-pty": ["bun-pty@0.4.8", "", {}, "sha512-rO70Mrbr13+jxHHHu2YBkk2pNqrJE5cJn29WE++PUr+GFA0hq/VgtQPZANJ8dJo6d7XImvBk37Innt8GM7O28w=="],
|
||||
|
||||
"bun-types": ["bun-types@1.3.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg=="],
|
||||
|
||||
"bun-webgpu": ["bun-webgpu@0.1.4", "", { "dependencies": { "@webgpu/types": "^0.1.60" }, "optionalDependencies": { "bun-webgpu-darwin-arm64": "^0.1.4", "bun-webgpu-darwin-x64": "^0.1.4", "bun-webgpu-linux-x64": "^0.1.4", "bun-webgpu-win32-x64": "^0.1.4" } }, "sha512-Kw+HoXl1PMWJTh9wvh63SSRofTA8vYBFCw0XEP1V1fFdQEDhI8Sgf73sdndE/oDpN/7CMx0Yv/q8FCvO39ROMQ=="],
|
||||
@@ -3266,6 +3264,8 @@
|
||||
|
||||
"named-placeholders": ["named-placeholders@1.1.6", "", { "dependencies": { "lru.min": "^1.1.0" } }, "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w=="],
|
||||
|
||||
"nan": ["nan@2.25.0", "", {}, "sha512-0M90Ag7Xn5KMLLZ7zliPWP3rT90P6PN+IzVFS0VqmnPktBk3700xUVv8Ikm9EUaUE5SDWdp/BIxdENzVznpm1g=="],
|
||||
|
||||
"nanoevents": ["nanoevents@7.0.1", "", {}, "sha512-o6lpKiCxLeijK4hgsqfR6CNToPyRU3keKyyI6uwuHRvpRTbZ0wXw51WRgyldVugZqoJfkGFrjrIenYH3bfEO3Q=="],
|
||||
|
||||
"nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
|
||||
@@ -3298,6 +3298,8 @@
|
||||
|
||||
"node-mock-http": ["node-mock-http@1.0.4", "", {}, "sha512-8DY+kFsDkNXy1sJglUfuODx1/opAGJGyrTuFqEoN90oRc2Vk0ZbD4K2qmKXBBEhZQzdKHIVfEJpDU8Ak2NJEvQ=="],
|
||||
|
||||
"node-pty": ["node-pty@1.0.0", "", { "dependencies": { "nan": "^2.17.0" } }, "sha512-wtBMWWS7dFZm/VgqElrTvtfMq4GzJ6+edFI0Y0zyzygUSZMgZdraDUMUhCIvkjhJjme15qWmbyJbtAx4ot4uZA=="],
|
||||
|
||||
"node-releases": ["node-releases@2.0.27", "", {}, "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA=="],
|
||||
|
||||
"nopt": ["nopt@7.2.1", "", { "dependencies": { "abbrev": "^2.0.0" }, "bin": { "nopt": "bin/nopt.js" } }, "sha512-taM24ViiimT/XntxbPyJQzCG+p4EKOpgD3mxFwW38mGjVUrfERQOeY4EDHjdnptttfHuHQXFx+lTP08Q+mLa/w=="],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-ai/app",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"description": "",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
|
||||
@@ -15,6 +15,40 @@ import { terminalWriter } from "@/utils/terminal-writer"
|
||||
|
||||
const TOGGLE_TERMINAL_ID = "terminal.toggle"
|
||||
const DEFAULT_TOGGLE_TERMINAL_KEYBIND = "ctrl+`"
|
||||
const FRAME_META = 0
|
||||
const FRAME_OUTPUT = 1
|
||||
const FRAME_INPUT = 2
|
||||
const encoder = new TextEncoder()
|
||||
|
||||
const connection = () => {
|
||||
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
|
||||
}
|
||||
|
||||
const frameInput = (id: string, data: string) => {
|
||||
const channel = encoder.encode(id)
|
||||
const body = encoder.encode(data)
|
||||
const out = new Uint8Array(2 + channel.length + body.length)
|
||||
out[0] = FRAME_INPUT
|
||||
out[1] = channel.length
|
||||
out.set(channel, 2)
|
||||
out.set(body, 2 + channel.length)
|
||||
return out
|
||||
}
|
||||
|
||||
const frameOutput = (bytes: Uint8Array, decoder: TextDecoder) => {
|
||||
if (bytes[0] !== FRAME_OUTPUT) return
|
||||
const size = bytes[1]
|
||||
if (!Number.isSafeInteger(size) || size < 0) return
|
||||
if (bytes.length < 2 + size) return
|
||||
return {
|
||||
connection: decoder.decode(bytes.subarray(2, 2 + size)),
|
||||
data: decoder.decode(bytes.subarray(2 + size)),
|
||||
}
|
||||
}
|
||||
|
||||
export interface TerminalProps extends ComponentProps<"div"> {
|
||||
pty: LocalPTY
|
||||
onSubmit?: () => void
|
||||
@@ -396,8 +430,10 @@ export const Terminal = (props: TerminalProps) => {
|
||||
scheduleSize(size.cols, size.rows)
|
||||
})
|
||||
cleanups.push(() => disposeIfDisposable(onResize))
|
||||
const connectionID = connection()
|
||||
const onData = t.onData((data) => {
|
||||
if (ws?.readyState === WebSocket.OPEN) ws.send(data)
|
||||
if (ws?.readyState !== WebSocket.OPEN) return
|
||||
ws.send(frameInput(connectionID, data))
|
||||
})
|
||||
cleanups.push(() => disposeIfDisposable(onData))
|
||||
const onKey = t.onKey((key) => {
|
||||
@@ -450,6 +486,7 @@ export const Terminal = (props: TerminalProps) => {
|
||||
const url = new URL(sdk.url + `/pty/${local.pty.id}/connect`)
|
||||
url.searchParams.set("directory", sdk.directory)
|
||||
url.searchParams.set("cursor", String(start !== undefined ? start : local.pty.buffer ? -1 : 0))
|
||||
url.searchParams.set("connection", connectionID)
|
||||
url.protocol = url.protocol === "https:" ? "wss:" : "ws:"
|
||||
url.username = server.current?.http.username ?? ""
|
||||
url.password = server.current?.http.password ?? ""
|
||||
@@ -471,24 +508,33 @@ export const Terminal = (props: TerminalProps) => {
|
||||
if (closing) return
|
||||
if (event.data instanceof ArrayBuffer) {
|
||||
const bytes = new Uint8Array(event.data)
|
||||
if (bytes[0] !== 0) return
|
||||
const json = decoder.decode(bytes.subarray(1))
|
||||
try {
|
||||
const meta = JSON.parse(json) as { cursor?: unknown }
|
||||
const next = meta?.cursor
|
||||
if (typeof next === "number" && Number.isSafeInteger(next) && next >= 0) {
|
||||
cursor = next
|
||||
if (bytes[0] === FRAME_META) {
|
||||
const json = decoder.decode(bytes.subarray(1))
|
||||
try {
|
||||
const meta = JSON.parse(json) as { cursor?: unknown; connection?: unknown }
|
||||
if (typeof meta?.connection === "string" && meta.connection !== connectionID) return
|
||||
const next = meta?.cursor
|
||||
if (typeof next === "number" && Number.isSafeInteger(next) && next >= 0) {
|
||||
cursor = next
|
||||
}
|
||||
} catch (err) {
|
||||
debugTerminal("invalid websocket control frame", err)
|
||||
}
|
||||
} catch (err) {
|
||||
debugTerminal("invalid websocket control frame", err)
|
||||
return
|
||||
}
|
||||
|
||||
const frame = frameOutput(bytes, decoder)
|
||||
if (!frame) return
|
||||
if (frame.connection !== connectionID) return
|
||||
if (!frame.data) return
|
||||
output?.push(frame.data)
|
||||
cursor += frame.data.length
|
||||
return
|
||||
}
|
||||
|
||||
const data = typeof event.data === "string" ? event.data : ""
|
||||
if (!data) return
|
||||
output?.push(data)
|
||||
cursor += data.length
|
||||
if (typeof event.data === "string") {
|
||||
debugTerminal("ignoring unframed websocket output")
|
||||
}
|
||||
}
|
||||
socket.addEventListener("message", handleMessage)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-ai/console-app",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode-ai/console-core",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-ai/console-function",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-ai/console-mail",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"dependencies": {
|
||||
"@jsx-email/all": "2.2.3",
|
||||
"@jsx-email/cli": "1.4.3",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@opencode-ai/desktop",
|
||||
"private": true,
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-ai/enterprise",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
id = "opencode"
|
||||
name = "OpenCode"
|
||||
description = "The open source coding agent."
|
||||
version = "1.2.8"
|
||||
version = "1.2.7"
|
||||
schema_version = 1
|
||||
authors = ["Anomaly"]
|
||||
repository = "https://github.com/anomalyco/opencode"
|
||||
@@ -11,26 +11,26 @@ name = "OpenCode"
|
||||
icon = "./icons/opencode.svg"
|
||||
|
||||
[agent_servers.opencode.targets.darwin-aarch64]
|
||||
archive = "https://github.com/anomalyco/opencode/releases/download/v1.2.8/opencode-darwin-arm64.zip"
|
||||
archive = "https://github.com/anomalyco/opencode/releases/download/v1.2.7/opencode-darwin-arm64.zip"
|
||||
cmd = "./opencode"
|
||||
args = ["acp"]
|
||||
|
||||
[agent_servers.opencode.targets.darwin-x86_64]
|
||||
archive = "https://github.com/anomalyco/opencode/releases/download/v1.2.8/opencode-darwin-x64.zip"
|
||||
archive = "https://github.com/anomalyco/opencode/releases/download/v1.2.7/opencode-darwin-x64.zip"
|
||||
cmd = "./opencode"
|
||||
args = ["acp"]
|
||||
|
||||
[agent_servers.opencode.targets.linux-aarch64]
|
||||
archive = "https://github.com/anomalyco/opencode/releases/download/v1.2.8/opencode-linux-arm64.tar.gz"
|
||||
archive = "https://github.com/anomalyco/opencode/releases/download/v1.2.7/opencode-linux-arm64.tar.gz"
|
||||
cmd = "./opencode"
|
||||
args = ["acp"]
|
||||
|
||||
[agent_servers.opencode.targets.linux-x86_64]
|
||||
archive = "https://github.com/anomalyco/opencode/releases/download/v1.2.8/opencode-linux-x64.tar.gz"
|
||||
archive = "https://github.com/anomalyco/opencode/releases/download/v1.2.7/opencode-linux-x64.tar.gz"
|
||||
cmd = "./opencode"
|
||||
args = ["acp"]
|
||||
|
||||
[agent_servers.opencode.targets.windows-x86_64]
|
||||
archive = "https://github.com/anomalyco/opencode/releases/download/v1.2.8/opencode-windows-x64.zip"
|
||||
archive = "https://github.com/anomalyco/opencode/releases/download/v1.2.7/opencode-windows-x64.zip"
|
||||
cmd = "./opencode.exe"
|
||||
args = ["acp"]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-ai/function",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"name": "opencode",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
@@ -100,7 +100,7 @@
|
||||
"ai": "catalog:",
|
||||
"ai-gateway-provider": "2.3.1",
|
||||
"bonjour-service": "1.3.0",
|
||||
"bun-pty": "0.4.8",
|
||||
"node-pty": "1.0.0",
|
||||
"chokidar": "4.0.3",
|
||||
"clipboardy": "4.0.0",
|
||||
"decimal.js": "10.5.0",
|
||||
|
||||
@@ -332,6 +332,7 @@ export const AuthLoginCommand = cmd({
|
||||
value: x.id,
|
||||
hint: {
|
||||
opencode: "recommended",
|
||||
anthropic: "Claude Max or API key",
|
||||
openai: "ChatGPT Plus/Pro or API key",
|
||||
}[x.id],
|
||||
})),
|
||||
|
||||
@@ -16,6 +16,8 @@ import { gitlabAuthPlugin as GitlabAuthPlugin } from "@gitlab/opencode-gitlab-au
|
||||
export namespace Plugin {
|
||||
const log = Log.create({ service: "plugin" })
|
||||
|
||||
const BUILTIN = ["opencode-anthropic-auth@0.0.13"]
|
||||
|
||||
// Built-in plugins that are directly imported (not installed from npm)
|
||||
const INTERNAL_PLUGINS: PluginInstance[] = [CodexAuthPlugin, CopilotAuthPlugin, GitlabAuthPlugin]
|
||||
|
||||
@@ -45,6 +47,9 @@ export namespace Plugin {
|
||||
|
||||
let plugins = config.plugin ?? []
|
||||
if (plugins.length) await Config.waitForDependencies()
|
||||
if (!Flag.OPENCODE_DISABLE_DEFAULT_PLUGINS) {
|
||||
plugins = [...BUILTIN, ...plugins]
|
||||
}
|
||||
|
||||
for (let plugin of plugins) {
|
||||
// ignore old codex plugin since it is supported first party now
|
||||
@@ -54,7 +59,24 @@ export namespace Plugin {
|
||||
const lastAtIndex = plugin.lastIndexOf("@")
|
||||
const pkg = lastAtIndex > 0 ? plugin.substring(0, lastAtIndex) : plugin
|
||||
const version = lastAtIndex > 0 ? plugin.substring(lastAtIndex + 1) : "latest"
|
||||
plugin = await BunProc.install(pkg, version)
|
||||
const builtin = BUILTIN.some((x) => x.startsWith(pkg + "@"))
|
||||
plugin = await BunProc.install(pkg, version).catch((err) => {
|
||||
if (!builtin) throw err
|
||||
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
log.error("failed to install builtin plugin", {
|
||||
pkg,
|
||||
version,
|
||||
error: message,
|
||||
})
|
||||
Bus.publish(Session.Event.Error, {
|
||||
error: new NamedError.Unknown({
|
||||
message: `Failed to install built-in plugin ${pkg}@${version}: ${message}`,
|
||||
}).toObject(),
|
||||
})
|
||||
|
||||
return ""
|
||||
})
|
||||
if (!plugin) continue
|
||||
}
|
||||
const mod = await import(plugin)
|
||||
|
||||
@@ -122,7 +122,8 @@ export namespace Provider {
|
||||
autoload: false,
|
||||
options: {
|
||||
headers: {
|
||||
"anthropic-beta": "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
|
||||
"anthropic-beta":
|
||||
"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { BusEvent } from "@/bus/bus-event"
|
||||
import { Bus } from "@/bus"
|
||||
import { type IPty } from "bun-pty"
|
||||
import { type IPty } from "node-pty"
|
||||
import z from "zod"
|
||||
import { Identifier } from "../id/id"
|
||||
import { Log } from "../util/log"
|
||||
import { Instance } from "../project/instance"
|
||||
import { lazy } from "@opencode-ai/util/lazy"
|
||||
import { Shell } from "@/shell/shell"
|
||||
import { Plugin } from "@/plugin"
|
||||
|
||||
@@ -15,22 +14,27 @@ export namespace Pty {
|
||||
const BUFFER_LIMIT = 1024 * 1024 * 2
|
||||
const BUFFER_CHUNK = 64 * 1024
|
||||
const encoder = new TextEncoder()
|
||||
const decoder = new TextDecoder()
|
||||
const FRAME_META = 0
|
||||
const FRAME_OUTPUT = 1
|
||||
const FRAME_INPUT = 2
|
||||
const MAX_CONNECTION = 200
|
||||
|
||||
type Socket = {
|
||||
readyState: number
|
||||
data?: unknown
|
||||
send: (data: string | Uint8Array | ArrayBuffer) => void
|
||||
close: (code?: number, reason?: string) => void
|
||||
}
|
||||
|
||||
type Subscriber = {
|
||||
id: number
|
||||
token: unknown
|
||||
connection: string
|
||||
}
|
||||
|
||||
const sockets = new WeakMap<object, number>()
|
||||
const owners = new WeakMap<object, string>()
|
||||
let socketCounter = 0
|
||||
let connectionCounter = 0
|
||||
|
||||
const tagSocket = (ws: Socket) => {
|
||||
if (!ws || typeof ws !== "object") return
|
||||
@@ -39,33 +43,74 @@ export namespace Pty {
|
||||
return next
|
||||
}
|
||||
|
||||
const token = (ws: Socket) => {
|
||||
const data = ws.data
|
||||
if (!data || typeof data !== "object") return
|
||||
|
||||
const events = (data as { events?: unknown }).events
|
||||
if (events && typeof events === "object") return events
|
||||
|
||||
const url = (data as { url?: unknown }).url
|
||||
if (url && typeof url === "object") return url
|
||||
|
||||
return data
|
||||
const connection = () => {
|
||||
connectionCounter = (connectionCounter + 1) % Number.MAX_SAFE_INTEGER
|
||||
return `${Date.now().toString(36)}-${connectionCounter.toString(36)}`
|
||||
}
|
||||
|
||||
// WebSocket control frame: 0x00 + UTF-8 JSON.
|
||||
const meta = (cursor: number) => {
|
||||
const json = JSON.stringify({ cursor })
|
||||
const normalizeConnection = (value?: string) => {
|
||||
const next = typeof value === "string" ? value.trim() : ""
|
||||
if (!next) return connection()
|
||||
if (next.length > MAX_CONNECTION) return connection()
|
||||
if (encoder.encode(next).length > 255) return connection()
|
||||
return next
|
||||
}
|
||||
|
||||
const output = (connection: string, data: string) => {
|
||||
const channel = encoder.encode(connection)
|
||||
const chunk = encoder.encode(data)
|
||||
const out = new Uint8Array(2 + channel.length + chunk.length)
|
||||
out[0] = FRAME_OUTPUT
|
||||
out[1] = channel.length
|
||||
out.set(channel, 2)
|
||||
out.set(chunk, 2 + channel.length)
|
||||
return out
|
||||
}
|
||||
|
||||
const input = (message: string | Uint8Array | ArrayBuffer) => {
|
||||
if (typeof message === "string") {
|
||||
return { data: message }
|
||||
}
|
||||
|
||||
const bytes = message instanceof Uint8Array ? message : new Uint8Array(message)
|
||||
if (bytes[0] !== FRAME_INPUT) return
|
||||
const size = bytes[1]
|
||||
if (!Number.isSafeInteger(size) || size < 0) return
|
||||
if (bytes.length < 2 + size) return
|
||||
return {
|
||||
connection: decoder.decode(bytes.subarray(2, 2 + size)),
|
||||
data: decoder.decode(bytes.subarray(2 + size)),
|
||||
}
|
||||
}
|
||||
|
||||
// WebSocket control frame: 0x00 + UTF-8 JSON ({ cursor, connection }).
|
||||
const meta = (cursor: number, connection: string) => {
|
||||
const json = JSON.stringify({ cursor, connection })
|
||||
const bytes = encoder.encode(json)
|
||||
const out = new Uint8Array(bytes.length + 1)
|
||||
out[0] = 0
|
||||
out[0] = FRAME_META
|
||||
out.set(bytes, 1)
|
||||
return out
|
||||
}
|
||||
|
||||
const pty = lazy(async () => {
|
||||
const { spawn } = await import("bun-pty")
|
||||
return spawn
|
||||
})
|
||||
type Spawn = (file: string, args: string | string[], options: unknown) => IPty
|
||||
let override: Spawn | undefined
|
||||
let spawn: Spawn | undefined
|
||||
|
||||
const pty = async (): Promise<Spawn> => {
|
||||
if (override) return override
|
||||
if (spawn) return spawn
|
||||
const mod = await import("node-pty")
|
||||
const next = mod.spawn as Spawn
|
||||
spawn = next
|
||||
return next
|
||||
}
|
||||
|
||||
export function setSpawn(input?: Spawn) {
|
||||
override = input
|
||||
if (input) return
|
||||
spawn = undefined
|
||||
}
|
||||
|
||||
export const Info = z
|
||||
.object({
|
||||
@@ -210,13 +255,8 @@ export namespace Pty {
|
||||
continue
|
||||
}
|
||||
|
||||
if (sub.token !== undefined && token(ws) !== sub.token) {
|
||||
session.subscribers.delete(ws)
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
ws.send(chunk)
|
||||
ws.send(output(sub.connection, chunk))
|
||||
} catch {
|
||||
session.subscribers.delete(ws)
|
||||
}
|
||||
@@ -292,7 +332,7 @@ export namespace Pty {
|
||||
}
|
||||
}
|
||||
|
||||
export function connect(id: string, ws: Socket, cursor?: number) {
|
||||
export function connect(id: string, ws: Socket, cursor?: number, connectionID?: string) {
|
||||
const session = state().get(id)
|
||||
if (!session) {
|
||||
ws.close()
|
||||
@@ -312,7 +352,11 @@ export namespace Pty {
|
||||
}
|
||||
|
||||
owners.set(ws, id)
|
||||
session.subscribers.set(ws, { id: socketId, token: token(ws) })
|
||||
const sub = {
|
||||
id: socketId,
|
||||
connection: normalizeConnection(connectionID),
|
||||
}
|
||||
session.subscribers.set(ws, sub)
|
||||
|
||||
const cleanup = () => {
|
||||
session.subscribers.delete(ws)
|
||||
@@ -336,7 +380,7 @@ export namespace Pty {
|
||||
if (data) {
|
||||
try {
|
||||
for (let i = 0; i < data.length; i += BUFFER_CHUNK) {
|
||||
ws.send(data.slice(i, i + BUFFER_CHUNK))
|
||||
ws.send(output(sub.connection, data.slice(i, i + BUFFER_CHUNK)))
|
||||
}
|
||||
} catch {
|
||||
cleanup()
|
||||
@@ -346,15 +390,18 @@ export namespace Pty {
|
||||
}
|
||||
|
||||
try {
|
||||
ws.send(meta(end))
|
||||
ws.send(meta(end, sub.connection))
|
||||
} catch {
|
||||
cleanup()
|
||||
ws.close()
|
||||
return
|
||||
}
|
||||
return {
|
||||
onMessage: (message: string | ArrayBuffer) => {
|
||||
session.process.write(String(message))
|
||||
onMessage: (message: string | Uint8Array | ArrayBuffer) => {
|
||||
const next = input(message)
|
||||
if (!next?.data) return
|
||||
if (next.connection && next.connection !== sub.connection) return
|
||||
session.process.write(next.data)
|
||||
},
|
||||
onClose: () => {
|
||||
log.info("client disconnected from session", { id })
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { Hono } from "hono"
|
||||
import { describeRoute, validator, resolver } from "hono-openapi"
|
||||
import { upgradeWebSocket } from "hono/bun"
|
||||
import z from "zod"
|
||||
import { Pty } from "@/pty"
|
||||
import { NotFoundError } from "../../storage/db"
|
||||
import { errors } from "../error"
|
||||
import { lazy } from "../../util/lazy"
|
||||
import { upgradeWebSocket } from "../websocket"
|
||||
|
||||
export const PtyRoutes = lazy(() =>
|
||||
new Hono()
|
||||
@@ -158,6 +158,12 @@ export const PtyRoutes = lazy(() =>
|
||||
if (!Number.isSafeInteger(parsed) || parsed < -1) return
|
||||
return parsed
|
||||
})()
|
||||
const connection = (() => {
|
||||
const value = c.req.query("connection")
|
||||
if (!value) return
|
||||
if (value.length > 200) return
|
||||
return value
|
||||
})()
|
||||
let handler: ReturnType<typeof Pty.connect>
|
||||
if (!Pty.get(id)) throw new Error("Session not found")
|
||||
|
||||
@@ -177,15 +183,20 @@ export const PtyRoutes = lazy(() =>
|
||||
|
||||
return {
|
||||
onOpen(_event, ws) {
|
||||
const socket = ws.raw
|
||||
if (!isSocket(socket)) {
|
||||
if (!isSocket(ws)) {
|
||||
ws.close()
|
||||
return
|
||||
}
|
||||
handler = Pty.connect(id, socket, cursor)
|
||||
handler = Pty.connect(id, ws, cursor, connection)
|
||||
},
|
||||
onMessage(event) {
|
||||
if (typeof event.data !== "string") return
|
||||
if (
|
||||
typeof event.data !== "string" &&
|
||||
!(event.data instanceof ArrayBuffer) &&
|
||||
!(event.data instanceof Uint8Array)
|
||||
) {
|
||||
return
|
||||
}
|
||||
handler?.onMessage(event.data)
|
||||
},
|
||||
onClose() {
|
||||
|
||||
@@ -33,7 +33,7 @@ import { lazy } from "../util/lazy"
|
||||
import { InstanceBootstrap } from "../project/bootstrap"
|
||||
import { NotFoundError } from "../storage/db"
|
||||
import type { ContentfulStatusCode } from "hono/utils/http-status"
|
||||
import { websocket } from "hono/bun"
|
||||
import { websocket } from "./websocket"
|
||||
import { HTTPException } from "hono/http-exception"
|
||||
import { errors } from "./error"
|
||||
import { QuestionRoutes } from "./routes/question"
|
||||
|
||||
1
packages/opencode/src/server/websocket.ts
Normal file
1
packages/opencode/src/server/websocket.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { createBunWebSocket, upgradeWebSocket, websocket } from "hono/bun"
|
||||
@@ -210,12 +210,18 @@ export namespace LLM {
|
||||
maxOutputTokens,
|
||||
abortSignal: input.abort,
|
||||
headers: {
|
||||
...(input.model.providerID.startsWith("opencode") && {
|
||||
"x-opencode-project": Instance.project.id,
|
||||
"x-opencode-session": input.sessionID,
|
||||
"x-opencode-request": input.user.id,
|
||||
"x-opencode-client": Flag.OPENCODE_CLIENT,
|
||||
}),
|
||||
...(input.model.providerID.startsWith("opencode")
|
||||
? {
|
||||
"x-opencode-project": Instance.project.id,
|
||||
"x-opencode-session": input.sessionID,
|
||||
"x-opencode-request": input.user.id,
|
||||
"x-opencode-client": Flag.OPENCODE_CLIENT,
|
||||
}
|
||||
: input.model.providerID !== "anthropic"
|
||||
? {
|
||||
"User-Agent": `opencode/${Installation.VERSION}`,
|
||||
}
|
||||
: undefined),
|
||||
...input.model.headers,
|
||||
...headers,
|
||||
},
|
||||
|
||||
166
packages/opencode/src/session/prompt/anthropic-20250930.txt
Normal file
166
packages/opencode/src/session/prompt/anthropic-20250930.txt
Normal file
@@ -0,0 +1,166 @@
|
||||
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: Assist with defensive security tasks only. Refuse to create, modify, or improve code that may be used maliciously. Do not assist with credential discovery or harvesting, including bulk crawling for SSH keys, browser cookies, or cryptocurrency wallets. Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation.
|
||||
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 Claude Code
|
||||
- To give feedback, users should report the issue at https://github.com/anthropics/claude-code/issues
|
||||
|
||||
When the user directly asks about Claude Code (eg. "can Claude Code do...", "does Claude Code have..."), or asks in second person (eg. "are you able...", "can you do..."), or asks how to use a specific Claude Code feature (eg. implement a hook, or write a slash command), use the WebFetch tool to gather information to answer the question from Claude Code docs. The list of available docs is available at https://docs.claude.com/en/docs/claude-code/claude_code_docs_map.md.
|
||||
|
||||
# Tone and style
|
||||
You should be concise, direct, and to the point, while providing complete information and matching the level of detail you provide in your response with the level of complexity of the user's query or the work you have completed.
|
||||
A concise response is generally less than 4 lines, not including tool calls or code generated. You should provide more detail when the task is complex or when the user asks you to.
|
||||
IMPORTANT: You should minimize output tokens as much as possible while maintaining helpfulness, quality, and accuracy. Only address the specific task at hand, avoiding tangential information unless absolutely critical for completing the request. If you can answer in 1-3 sentences or a short paragraph, please do.
|
||||
IMPORTANT: You should NOT answer with unnecessary preamble or postamble (such as explaining your code or summarizing your action), unless the user asks you to.
|
||||
Do not add additional code explanation summary unless requested by the user. After working on a file, briefly confirm that you have completed the task, rather than providing an explanation of what you did.
|
||||
Answer the user's question directly, avoiding any elaboration, explanation, introduction, conclusion, or excessive details. Brief answers are best, but be sure to provide complete information. You MUST avoid extra preamble before/after your response, such as "The answer is <answer>.", "Here is the content of the file..." or "Based on the information provided, the answer is..." or "Here is what I will do next...".
|
||||
|
||||
Here are some examples to demonstrate appropriate verbosity:
|
||||
<example>
|
||||
user: 2 + 2
|
||||
assistant: 4
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: what is 2+2?
|
||||
assistant: 4
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: is 11 a prime number?
|
||||
assistant: Yes
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: what command should I run to list files in the current directory?
|
||||
assistant: ls
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: what command should I run to watch files in the current directory?
|
||||
assistant: [runs ls to list the files in the current directory, then read docs/commands in the relevant file to find out how to watch files]
|
||||
npm run dev
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: How many golf balls fit inside a jetta?
|
||||
assistant: 150000
|
||||
</example>
|
||||
|
||||
<example>
|
||||
user: what files are in the directory src/?
|
||||
assistant: [runs ls and sees foo.c, bar.c, baz.c]
|
||||
user: which file contains the implementation of foo?
|
||||
assistant: src/foo.c
|
||||
</example>
|
||||
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:
|
||||
- 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.
|
||||
|
||||
# Professional objectivity
|
||||
Prioritize technical accuracy and truthfulness over validating the user's beliefs. Focus on facts and problem-solving, providing direct, objective technical info without any unnecessary superlatives, praise, or emotional validation. It is best for the user if Claude honestly applies the same rigorous standards to all ideas and disagrees when necessary, even if it may not be what the user wants to hear. Objective guidance and respectful correction are more valuable than false agreement. Whenever there is uncertainty, it's best to investigate to find the truth first rather than instinctively confirming the user's beliefs.
|
||||
|
||||
# Task Management
|
||||
You have access to the TodoWrite tools to help you manage and plan tasks. Use these tools VERY frequently to ensure that you are tracking your tasks and giving the user visibility into your progress.
|
||||
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.
|
||||
|
||||
Examples:
|
||||
|
||||
<example>
|
||||
user: Run the build and fix any type errors
|
||||
assistant: I'm going to use the TodoWrite tool to write the following items to the todo list:
|
||||
- Run the build
|
||||
- Fix any type errors
|
||||
|
||||
I'm now going to run the build using Bash.
|
||||
|
||||
Looks like I found 10 type errors. I'm going to use the TodoWrite tool to write 10 items to the todo list.
|
||||
|
||||
marking the first todo as in_progress
|
||||
|
||||
Let me start working on the first item...
|
||||
|
||||
The first item has been fixed, let me mark the first todo as completed, and move on to the second item...
|
||||
..
|
||||
..
|
||||
</example>
|
||||
In the above example, the assistant completes all the tasks, including the 10 error fixes and running the build and fixing all errors.
|
||||
|
||||
<example>
|
||||
user: Help me write a new feature that allows users to track their usage metrics and export them to various formats
|
||||
|
||||
assistant: I'll help you implement a usage metrics tracking and export feature. Let me first use the TodoWrite tool to plan this task.
|
||||
Adding the following todos to the todo list:
|
||||
1. Research existing metrics tracking in the codebase
|
||||
2. Design the metrics collection system
|
||||
3. Implement core metrics tracking functionality
|
||||
4. Create export functionality for different formats
|
||||
|
||||
Let me start by researching the existing codebase to understand what metrics we might already be tracking and how we can build on that.
|
||||
|
||||
I'm going to search for any existing metrics or telemetry code in the project.
|
||||
|
||||
I've found some existing telemetry code. Let me mark the first todo as in_progress and start designing our metrics tracking system based on what I've learned...
|
||||
|
||||
[Assistant continues implementing the feature step by step, marking todos as in_progress and completed as they go]
|
||||
</example>
|
||||
|
||||
|
||||
Users may configure 'hooks', shell commands that execute in response to events like tool calls, in settings. Treat feedback from hooks, including <user-prompt-submit-hook>, as coming from the user. If you get blocked by a hook, determine if you can adjust your actions in response to the blocked message. If not, ask the user to check their hooks configuration.
|
||||
|
||||
# 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
|
||||
|
||||
- Tool results and user messages may include <system-reminder> tags. <system-reminder> tags contain useful information and reminders. They are automatically added by the system, and bear no direct relation to the specific tool results or user messages in which they appear.
|
||||
|
||||
|
||||
# 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.
|
||||
- If the user specifies that they want you to run tools "in parallel", you MUST send a single message with multiple tool use content blocks. For example, if you need to launch multiple agents in parallel, send a single message with multiple Task tool calls.
|
||||
- Use specialized tools instead of bash commands when possible, as this provides a better user experience. For file operations, use dedicated tools: Read for reading files instead of cat/head/tail, Edit for editing instead of sed/awk, and Write for creating files instead of cat with heredoc or echo redirection. Reserve bash tools exclusively for actual system commands and terminal operations that require shell execution. NEVER use bash echo or other command-line tools to communicate thoughts, explanations, or instructions to the user. Output all communication directly in your response text instead.
|
||||
|
||||
|
||||
Here is useful information about the environment you are running in:
|
||||
<env>
|
||||
Working directory: /home/thdxr/dev/projects/anomalyco/opencode/packages/opencode
|
||||
Is directory a git repo: Yes
|
||||
Platform: linux
|
||||
OS Version: Linux 6.12.4-arch1-1
|
||||
Today's date: 2025-09-30
|
||||
</env>
|
||||
You are powered by the model named Sonnet 4.5. The exact model ID is claude-sonnet-4-5-20250929.
|
||||
|
||||
Assistant knowledge cutoff is January 2025.
|
||||
|
||||
|
||||
IMPORTANT: Assist with defensive security tasks only. Refuse to create, modify, or improve code that may be used maliciously. Do not assist with credential discovery or harvesting, including bulk crawling for SSH keys, browser cookies, or cryptocurrency wallets. Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation.
|
||||
|
||||
|
||||
IMPORTANT: Always use the TodoWrite tool to plan and track tasks throughout the conversation.
|
||||
|
||||
# Code References
|
||||
|
||||
When referencing specific functions or pieces of code include the pattern `file_path:line_number` to allow the user to easily navigate to the source code location.
|
||||
|
||||
<example>
|
||||
user: Where are errors from the client handled?
|
||||
assistant: Clients are marked as failed in the `connectToServer` function in src/services/process.ts:712.
|
||||
</example>
|
||||
@@ -1,9 +1,73 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
|
||||
import { Instance } from "../../src/project/instance"
|
||||
import { Pty } from "../../src/pty"
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
|
||||
const encoder = new TextEncoder()
|
||||
const decoder = new TextDecoder()
|
||||
|
||||
const input = (connection: string, data: string) => {
|
||||
const channel = encoder.encode(connection)
|
||||
const body = encoder.encode(data)
|
||||
const out = new Uint8Array(2 + channel.length + body.length)
|
||||
out[0] = 2
|
||||
out[1] = channel.length
|
||||
out.set(channel, 2)
|
||||
out.set(body, 2 + channel.length)
|
||||
return out
|
||||
}
|
||||
|
||||
const output = (connection: string, data: unknown) => {
|
||||
if (typeof data === "string") return data
|
||||
if (!(data instanceof Uint8Array) && !(data instanceof ArrayBuffer)) return ""
|
||||
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data)
|
||||
if (bytes[0] !== 1) return ""
|
||||
const size = bytes[1]
|
||||
if (!Number.isSafeInteger(size) || size < 0) return ""
|
||||
if (bytes.length < 2 + size) return ""
|
||||
const id = decoder.decode(bytes.subarray(2, 2 + size))
|
||||
if (id !== connection) return ""
|
||||
return decoder.decode(bytes.subarray(2 + size))
|
||||
}
|
||||
|
||||
const spawn = () => {
|
||||
let pid = 1000
|
||||
return () => {
|
||||
const data = new Set<(chunk: string) => void>()
|
||||
const exit = new Set<(event: { exitCode: number }) => void>()
|
||||
let closed = false
|
||||
|
||||
return {
|
||||
pid: ++pid,
|
||||
onData: (cb: (chunk: string) => void) => {
|
||||
data.add(cb)
|
||||
},
|
||||
onExit: (cb: (event: { exitCode: number }) => void) => {
|
||||
exit.add(cb)
|
||||
},
|
||||
resize: () => {},
|
||||
write: (chunk: string) => {
|
||||
if (closed) return
|
||||
for (const cb of data) cb(chunk)
|
||||
},
|
||||
kill: () => {
|
||||
if (closed) return
|
||||
closed = true
|
||||
for (const cb of exit) cb({ exitCode: 0 })
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("pty", () => {
|
||||
beforeEach(() => {
|
||||
Pty.setSpawn(spawn() as unknown as Parameters<typeof Pty.setSpawn>[0])
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Pty.setSpawn()
|
||||
})
|
||||
|
||||
test("does not leak output when websocket objects are reused", async () => {
|
||||
await using dir = await tmpdir({ git: true })
|
||||
|
||||
@@ -18,9 +82,9 @@ describe("pty", () => {
|
||||
|
||||
const ws = {
|
||||
readyState: 1,
|
||||
data: { events: { connection: "a" } },
|
||||
send: (data: unknown) => {
|
||||
outA.push(typeof data === "string" ? data : Buffer.from(data as Uint8Array).toString("utf8"))
|
||||
const text = output("conn-a", data)
|
||||
if (text) outA.push(text)
|
||||
},
|
||||
close: () => {
|
||||
// no-op (simulate abrupt drop)
|
||||
@@ -28,14 +92,14 @@ describe("pty", () => {
|
||||
}
|
||||
|
||||
// Connect "a" first with ws.
|
||||
Pty.connect(a.id, ws as any)
|
||||
Pty.connect(a.id, ws as any, undefined, "conn-a")
|
||||
|
||||
// Now "reuse" the same ws object for another connection.
|
||||
ws.data = { events: { connection: "b" } }
|
||||
ws.send = (data: unknown) => {
|
||||
outB.push(typeof data === "string" ? data : Buffer.from(data as Uint8Array).toString("utf8"))
|
||||
const text = output("conn-b", data)
|
||||
if (text) outB.push(text)
|
||||
}
|
||||
Pty.connect(b.id, ws as any)
|
||||
Pty.connect(b.id, ws as any, undefined, "conn-b")
|
||||
|
||||
// Clear connect metadata writes.
|
||||
outA.length = 0
|
||||
@@ -54,7 +118,7 @@ describe("pty", () => {
|
||||
})
|
||||
})
|
||||
|
||||
test("does not leak output when Bun recycles websocket objects before re-connect", async () => {
|
||||
test("does not leak output when websocket objects are recycled before re-connect", async () => {
|
||||
await using dir = await tmpdir({ git: true })
|
||||
|
||||
await Instance.provide({
|
||||
@@ -67,9 +131,9 @@ describe("pty", () => {
|
||||
|
||||
const ws = {
|
||||
readyState: 1,
|
||||
data: { events: { connection: "a" } },
|
||||
send: (data: unknown) => {
|
||||
outA.push(typeof data === "string" ? data : Buffer.from(data as Uint8Array).toString("utf8"))
|
||||
const text = output("conn-a", data)
|
||||
if (text) outA.push(text)
|
||||
},
|
||||
close: () => {
|
||||
// no-op (simulate abrupt drop)
|
||||
@@ -77,14 +141,14 @@ describe("pty", () => {
|
||||
}
|
||||
|
||||
// Connect "a" first.
|
||||
Pty.connect(a.id, ws as any)
|
||||
Pty.connect(a.id, ws as any, undefined, "conn-a")
|
||||
outA.length = 0
|
||||
|
||||
// Simulate Bun reusing the same websocket object for another
|
||||
// connection before the next onOpen calls Pty.connect.
|
||||
ws.data = { events: { connection: "b" } }
|
||||
// Simulate websocket object reuse for another connection before
|
||||
// the next onOpen calls Pty.connect.
|
||||
ws.send = (data: unknown) => {
|
||||
outB.push(typeof data === "string" ? data : Buffer.from(data as Uint8Array).toString("utf8"))
|
||||
const text = output("conn-b", data)
|
||||
if (text) outB.push(text)
|
||||
}
|
||||
|
||||
Pty.write(a.id, "AAA\n")
|
||||
@@ -97,4 +161,42 @@ describe("pty", () => {
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test("drops input frames that carry a different connection id", async () => {
|
||||
await using dir = await tmpdir({ git: true })
|
||||
|
||||
await Instance.provide({
|
||||
directory: dir.path,
|
||||
fn: async () => {
|
||||
const a = await Pty.create({ command: "cat", title: "a" })
|
||||
try {
|
||||
const out: string[] = []
|
||||
|
||||
const ws = {
|
||||
readyState: 1,
|
||||
send: (data: unknown) => {
|
||||
const text = output("conn-a", data)
|
||||
if (text) out.push(text)
|
||||
},
|
||||
close: () => {
|
||||
// no-op
|
||||
},
|
||||
}
|
||||
|
||||
const handler = Pty.connect(a.id, ws as any, undefined, "conn-a")
|
||||
out.length = 0
|
||||
|
||||
handler?.onMessage(input("conn-b", "BBB\n"))
|
||||
await Bun.sleep(100)
|
||||
expect(out.join("")).not.toContain("BBB")
|
||||
|
||||
handler?.onMessage(input("conn-a", "AAA\n"))
|
||||
await Bun.sleep(100)
|
||||
expect(out.join("")).toContain("AAA")
|
||||
} finally {
|
||||
await Pty.remove(a.id)
|
||||
}
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -307,6 +307,7 @@ describe("session.llm.stream", () => {
|
||||
expect(url.pathname.startsWith("/v1/")).toBe(true)
|
||||
expect(url.pathname.endsWith("/chat/completions")).toBe(true)
|
||||
expect(headers.get("Authorization")).toBe("Bearer test-key")
|
||||
expect(headers.get("User-Agent") ?? "").toMatch(/^opencode\//)
|
||||
|
||||
expect(body.model).toBe(resolved.api.id)
|
||||
expect(body.temperature).toBe(0.4)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode-ai/plugin",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/package.json",
|
||||
"name": "@opencode-ai/sdk",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-ai/slack",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-ai/ui",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"exports": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode-ai/util",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -178,30 +178,7 @@ export default defineConfig({
|
||||
"network",
|
||||
"enterprise",
|
||||
"troubleshooting",
|
||||
{
|
||||
label: "Windows",
|
||||
translations: {
|
||||
en: "Windows",
|
||||
ar: "Windows",
|
||||
"bs-BA": "Windows",
|
||||
"da-DK": "Windows",
|
||||
"de-DE": "Windows",
|
||||
"es-ES": "Windows",
|
||||
"fr-FR": "Windows",
|
||||
"it-IT": "Windows",
|
||||
"ja-JP": "Windows",
|
||||
"ko-KR": "Windows",
|
||||
"nb-NO": "Windows",
|
||||
"pl-PL": "Windows",
|
||||
"pt-BR": "Windows",
|
||||
"ru-RU": "Windows",
|
||||
"th-TH": "Windows",
|
||||
"tr-TR": "Windows",
|
||||
"zh-CN": "Windows",
|
||||
"zh-TW": "Windows",
|
||||
},
|
||||
link: "windows-wsl",
|
||||
},
|
||||
"windows-wsl",
|
||||
{
|
||||
label: "Usage",
|
||||
translations: {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "@opencode-ai/web",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"dev:remote": "VITE_API_URL=https://api.opencode.ai astro dev",
|
||||
|
||||
@@ -135,8 +135,6 @@ Per usare Amazon Bedrock con OpenCode:
|
||||
|
||||
2. **Configura l'autenticazione** usando uno dei seguenti metodi:
|
||||
|
||||
***
|
||||
|
||||
#### Variabili d'ambiente (Avvio rapido)
|
||||
|
||||
Imposta una di queste variabili d'ambiente mentre esegui opencode:
|
||||
@@ -159,8 +157,6 @@ Per usare Amazon Bedrock con OpenCode:
|
||||
export AWS_REGION=us-east-1
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
#### File di configurazione (Consigliato)
|
||||
|
||||
Per configurazione specifica del progetto o persistente, usa `opencode.json`:
|
||||
@@ -188,8 +184,6 @@ Per usare Amazon Bedrock con OpenCode:
|
||||
Le opzioni del file di configurazione hanno la precedenza sulle variabili d'ambiente.
|
||||
:::
|
||||
|
||||
***
|
||||
|
||||
#### Avanzato: VPC Endpoints
|
||||
|
||||
Se stai usando VPC endpoints per Bedrock:
|
||||
@@ -213,16 +207,12 @@ Per usare Amazon Bedrock con OpenCode:
|
||||
L'opzione `endpoint` è un alias per l'opzione generica `baseURL`, usando terminologia specifica AWS. Se vengono specificati sia `endpoint` sia `baseURL`, `endpoint` ha la precedenza.
|
||||
:::
|
||||
|
||||
***
|
||||
|
||||
#### Metodi di autenticazione
|
||||
- **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Crea un utente IAM e genera chiavi di accesso nella Console AWS
|
||||
- **`AWS_PROFILE`**: Usa profili nominati da `~/.aws/credentials`. Configura prima con `aws configure --profile my-profile` o `aws sso login`
|
||||
- **`AWS_BEARER_TOKEN_BEDROCK`**: Genera chiavi API a lungo termine dalla console Amazon Bedrock
|
||||
- **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: Per EKS IRSA (IAM Roles for Service Accounts) o altri ambienti Kubernetes con federazione OIDC. Queste variabili d'ambiente vengono iniettate automaticamente da Kubernetes quando usi le annotazioni del service account.
|
||||
|
||||
***
|
||||
|
||||
#### Precedenza autenticazione
|
||||
|
||||
Amazon Bedrock usa la seguente priorità di autenticazione:
|
||||
@@ -240,8 +230,7 @@ Per usare Amazon Bedrock con OpenCode:
|
||||
```
|
||||
|
||||
:::note
|
||||
Per profili di inferenza personalizzati, usa il nome del modello e del provider nella chiave e imposta la proprietà `id` all'arn. Questo assicura una cache corretta.
|
||||
:::
|
||||
Per profili di inferenza personalizzati, usa il nome del modello e del provider nella chiave e imposta la proprietà `id` all'arn. Questo assicura una cache corretta:
|
||||
|
||||
```json title="opencode.json"
|
||||
{
|
||||
@@ -259,6 +248,8 @@ Per profili di inferenza personalizzati, usa il nome del modello e del provider
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
### Anthropic
|
||||
@@ -1170,8 +1161,6 @@ Per usare Kimi K2 di Moonshot AI:
|
||||
/models
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### MiniMax
|
||||
|
||||
1. Vai alla [MiniMax API Console](https://platform.minimax.io/login), crea un account e genera una chiave API.
|
||||
|
||||
@@ -131,8 +131,6 @@ OpenCode로 Amazon Bedrock을 사용하려면:
|
||||
|
||||
2. 다음 방법 중 하나를 사용하여 **설정**합니다:
|
||||
|
||||
---
|
||||
|
||||
### 환경 변수 (빠른 시작)
|
||||
|
||||
OpenCode를 실행하는 동안 다음 환경 변수 중 하나를 설정합니다:
|
||||
@@ -155,8 +153,6 @@ OpenCode를 실행하는 동안 다음 환경 변수 중 하나를 설정합니
|
||||
export AWS_REGION=us-east-1
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### 설정 파일 (권장)
|
||||
|
||||
프로젝트별 또는 영구 구성을 위해 `opencode.json`을 사용하십시오.
|
||||
@@ -185,8 +181,6 @@ OpenCode를 실행하는 동안 다음 환경 변수 중 하나를 설정합니
|
||||
구성 파일 옵션은 환경 변수보다 우선 순위가 높습니다.
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
#### 고급: VPC 엔드포인트
|
||||
|
||||
Bedrock의 VPC 엔드포인트를 사용하는 경우:
|
||||
@@ -210,8 +204,6 @@ Bedrock의 VPC 엔드포인트를 사용하는 경우:
|
||||
`endpoint` 옵션은 일반적인 `baseURL` 옵션의 별칭입니다. `endpoint`와 `baseURL` 둘 다 지정된 경우 `endpoint`가 우선합니다.
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
#### 인증 방법
|
||||
|
||||
- **`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`**: IAM 사용자 및 AWS 콘솔에서 액세스 키 생성
|
||||
@@ -219,8 +211,6 @@ Bedrock의 VPC 엔드포인트를 사용하는 경우:
|
||||
- **`AWS_BEARER_TOKEN_BEDROCK`**: Amazon Bedrock 콘솔에서 임시 API 키 생성
|
||||
- **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: EKS IRSA (서비스 계정용 IAM 역할) 또는 다른 Kubernetes 환경의 OIDC 연동. 이 환경 변수는 서비스 계정을 사용할 때 Kubernetes에 의해 자동으로 주입됩니다.
|
||||
|
||||
---
|
||||
|
||||
#### 인증 우선 순위
|
||||
|
||||
Amazon Bedrock은 다음과 같은 인증 우선 순위를 사용합니다.
|
||||
@@ -239,8 +229,7 @@ Amazon Bedrock은 다음과 같은 인증 우선 순위를 사용합니다.
|
||||
```
|
||||
|
||||
:::note
|
||||
사용자 정의 추론 프로필(custom inference profiles)의 경우, 키에 모델과 공급자 이름을 사용하고 `id` 속성에 ARN을 설정하십시오. 이렇게 하면 올바른 캐싱이 보장됩니다.
|
||||
:::
|
||||
사용자 정의 추론 프로필(custom inference profiles)의 경우, 키에 모델과 공급자 이름을 사용하고 `id` 속성에 ARN을 설정하십시오. 이렇게 하면 올바른 캐싱이 보장됩니다:
|
||||
|
||||
```json title="opencode.json"
|
||||
{
|
||||
@@ -258,6 +247,8 @@ Amazon Bedrock은 다음과 같은 인증 우선 순위를 사용합니다.
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
#### Anthropic
|
||||
@@ -666,8 +657,6 @@ GitLab Duo는 GitLab의 Anthropic 프록시를 통해 기본 도구 호출 기
|
||||
|
||||
**OAuth**를 선택하면 브라우저에서 권한 부여를 요청합니다.
|
||||
|
||||
---
|
||||
|
||||
### 개인 액세스 토큰 사용
|
||||
|
||||
1. [GitLab User Settings > Access Tokens](https://gitlab.com/-/user_settings/personal_access_tokens)로 이동
|
||||
|
||||
@@ -135,8 +135,6 @@ To use Amazon Bedrock with OpenCode:
|
||||
|
||||
2. **Configure authentication** using one of the following methods:
|
||||
|
||||
***
|
||||
|
||||
#### Environment Variables (Quick Start)
|
||||
|
||||
Set one of these environment variables while running opencode:
|
||||
@@ -159,8 +157,6 @@ To use Amazon Bedrock with OpenCode:
|
||||
export AWS_REGION=us-east-1
|
||||
```
|
||||
|
||||
***
|
||||
|
||||
#### Configuration File (Recommended)
|
||||
|
||||
For project-specific or persistent configuration, use `opencode.json`:
|
||||
@@ -188,8 +184,6 @@ To use Amazon Bedrock with OpenCode:
|
||||
Configuration file options take precedence over environment variables.
|
||||
:::
|
||||
|
||||
***
|
||||
|
||||
#### Advanced: VPC Endpoints
|
||||
|
||||
If you're using VPC endpoints for Bedrock:
|
||||
@@ -213,16 +207,12 @@ To use Amazon Bedrock with OpenCode:
|
||||
The `endpoint` option is an alias for the generic `baseURL` option, using AWS-specific terminology. If both `endpoint` and `baseURL` are specified, `endpoint` takes precedence.
|
||||
:::
|
||||
|
||||
***
|
||||
|
||||
#### Authentication Methods
|
||||
- **`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`**: Create an IAM user and generate access keys in the AWS Console
|
||||
- **`AWS_PROFILE`**: Use named profiles from `~/.aws/credentials`. First configure with `aws configure --profile my-profile` or `aws sso login`
|
||||
- **`AWS_BEARER_TOKEN_BEDROCK`**: Generate long-term API keys from the Amazon Bedrock console
|
||||
- **`AWS_WEB_IDENTITY_TOKEN_FILE` / `AWS_ROLE_ARN`**: For EKS IRSA (IAM Roles for Service Accounts) or other Kubernetes environments with OIDC federation. These environment variables are automatically injected by Kubernetes when using service account annotations.
|
||||
|
||||
***
|
||||
|
||||
#### Authentication Precedence
|
||||
|
||||
Amazon Bedrock uses the following authentication priority:
|
||||
@@ -240,8 +230,7 @@ To use Amazon Bedrock with OpenCode:
|
||||
```
|
||||
|
||||
:::note
|
||||
For custom inference profiles, use the model and provider name in the key and set the `id` property to the arn. This ensures correct caching.
|
||||
:::
|
||||
For custom inference profiles, use the model and provider name in the key and set the `id` property to the arn. This ensures correct caching:
|
||||
|
||||
```json title="opencode.json"
|
||||
{
|
||||
@@ -259,6 +248,8 @@ For custom inference profiles, use the model and provider name in the key and se
|
||||
}
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
---
|
||||
|
||||
### Anthropic
|
||||
@@ -275,6 +266,8 @@ For custom inference profiles, use the model and provider name in the key and se
|
||||
```txt
|
||||
┌ Select auth method
|
||||
│
|
||||
│ Claude Pro/Max
|
||||
│ Create an API Key
|
||||
│ Manually enter API Key
|
||||
└
|
||||
```
|
||||
@@ -286,16 +279,14 @@ For custom inference profiles, use the model and provider name in the key and se
|
||||
```
|
||||
|
||||
:::info
|
||||
There are plugins that allow you to use your Claude Pro/Max models with
|
||||
OpenCode. Anthropic explicitly prohibits this.
|
||||
Using your Claude Pro/Max subscription in OpenCode is not officially supported by [Anthropic](https://anthropic.com).
|
||||
:::
|
||||
|
||||
Other companies support freedom of choice with developer tooling - you can use
|
||||
the following subscriptions in OpenCode with zero setup:
|
||||
##### Using API keys
|
||||
|
||||
- ChatGPT Plus
|
||||
- Github Copilot
|
||||
- Gitlab Duo
|
||||
:::
|
||||
You can also select **Create an API Key** if you don't have a Pro/Max subscription. It'll also open your browser and ask you to login to Anthropic and give you a code you can paste in your terminal.
|
||||
|
||||
Or if you already have an API key, you can select **Manually enter API Key** and paste it in your terminal.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "opencode",
|
||||
"displayName": "opencode",
|
||||
"description": "opencode for VS Code",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.7",
|
||||
"publisher": "sst-dev",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
Reference in New Issue
Block a user