Compare commits

...
27 Commits
Author SHA1 Message Date
Dax Raad 085c0e4e2b respect go.work when spawning LSP
publish / publish (push) Has been cancelled
2025-07-09 22:54:47 -04:00
Dax Raad 8404a97c3e better detection of prettier formatter
publish / publish (push) Has been cancelled
2025-07-09 22:37:31 -04:00
Dax Raad 0ee3b1ede2 do not wait for LSP to be fully ready
publish / publish (push) Has been cancelled
2025-07-09 21:59:38 -04:00
Dax Raad a826936702 modes concept 2025-07-09 21:59:38 -04:00
Jay V fd4a5d5a63 docs: share doc edit 2025-07-09 20:26:31 -04:00
Jay V 69cf1d7b7e docs: share doc 2025-07-09 20:24:09 -04:00
Jay V 8e0a1d1167 docs: edit troubleshooting 2025-07-09 19:55:14 -04:00
Timo ClasenandGitHub f22021187d feat(tui): treat pasted text file paths as file references (#809) 2025-07-09 18:37:39 -05:00
Jay V febecc348a docs: enterprise doc 2025-07-09 15:46:57 -04:00
Jay V c5ccfc3e94 docs: share page last part fix 2025-07-09 15:46:57 -04:00
1f6efc6b94 Add gpt-4.1 beast prompt (#778)
publish / publish (push) Has been cancelled
Co-authored-by: Dax Raad <d@ironbay.co>
2025-07-09 12:11:54 -04:00
Frank DenisandGitHub 727fe6f942 LSP: fix SimpleRoots to actually search in the root directory (#795) 2025-07-09 10:35:06 -05:00
Dax Raad a91e79382e ci: remove checked in config.schema.json 2025-07-09 11:30:42 -04:00
Dax Raad 5c626e0a2f ci: generate config schema as part of build 2025-07-09 11:25:58 -04:00
adamdottv 8e9e383219 chore: troubleshooting docs 2025-07-09 10:12:36 -05:00
Dax Raad f383008cc1 lsp: spawn only a single tsserver in project root
publish / publish (push) Has been cancelled
2025-07-09 11:06:44 -04:00
adamdottv 303ade25ed feat: discord redirect 2025-07-09 10:01:42 -05:00
adamdottv 53f8e7850e feat: configurable log levels 2025-07-09 10:00:03 -05:00
adamdottv ca8ce88354 feat(tui): move logging to server logs 2025-07-09 08:16:10 -05:00
adamdottv 37a86439c4 fix(tui): don't panic on missing linux clipboard tool 2025-07-09 06:51:58 -05:00
adamdottv 269b43f4de fix(tui): markdown wrapping off sometimes 2025-07-09 06:41:53 -05:00
adamdottv 3f25e5bf86 chore: internal clipboard package 2025-07-09 04:55:24 -05:00
Aiden ClineandGitHub 67765fa47c tweak: keep completion options open when trigger is still present (#789) 2025-07-09 04:42:31 -05:00
adamdottv 58b1c58bc5 fix(tui): clear command priority
publish / publish (push) Has been cancelled
2025-07-08 19:26:50 -05:00
Dax Raad d80badc50f ci: ignore chore commits 2025-07-08 20:05:33 -04:00
Dax Raad 75279e5ccf wip: symbols endpoint 2025-07-08 20:05:33 -04:00
Yihui KhuuandGitHub 7893b84614 Add debounce before exit when using non-leader exit command (#759) 2025-07-08 18:53:38 -05:00
90 changed files with 1512 additions and 2540 deletions
+1 -1
View File
@@ -9,7 +9,7 @@
</p>
<p align="center">AI coding agent, built for the terminal.</p>
<p align="center">
<a href="https://discord.gg/opencode"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://opencode.ai/discord"><img alt="Discord" src="https://img.shields.io/discord/1391832426048651334?style=flat-square&label=discord" /></a>
<a href="https://www.npmjs.com/package/opencode-ai"><img alt="npm" src="https://img.shields.io/npm/v/opencode-ai?style=flat-square" /></a>
<a href="https://github.com/sst/opencode/actions/workflows/publish.yml"><img alt="Build status" src="https://img.shields.io/github/actions/workflow/status/sst/opencode/publish.yml?style=flat-square&branch=dev" /></a>
</p>
+2 -2
View File
@@ -83,7 +83,7 @@
"sharp": "0.32.5",
"shiki": "3.4.2",
"solid-js": "1.9.7",
"toolbeam-docs-theme": "0.4.1",
"toolbeam-docs-theme": "0.4.3",
},
"devDependencies": {
"@types/node": "catalog:",
@@ -1531,7 +1531,7 @@
"token-types": ["token-types@6.0.0", "", { "dependencies": { "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA=="],
"toolbeam-docs-theme": ["toolbeam-docs-theme@0.4.1", "", { "peerDependencies": { "@astrojs/starlight": "^0.34.3", "astro": "^5.7.13" } }, "sha512-lTI4dHZaVNQky29m7sb36Oy4tWPwxsCuFxFjF8hgGW0vpV+S6qPvI9SwsJFvdE/OHO5DoI7VMbryV1pxZHkkHQ=="],
"toolbeam-docs-theme": ["toolbeam-docs-theme@0.4.3", "", { "peerDependencies": { "@astrojs/starlight": "^0.34.3", "astro": "^5.7.13" } }, "sha512-3um/NsSq4xFeKbKrNGPHIzfTixwnEVvroqA8Q+lecnYHHJ5TtiYTggHDqewOW+I67t0J1IVBwVKUPjxiQfIcog=="],
"tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="],
-546
View File
@@ -1,546 +0,0 @@
{
"type": "object",
"properties": {
"$schema": {
"type": "string",
"description": "JSON schema reference for configuration validation"
},
"theme": {
"type": "string",
"description": "Theme name to use for the interface"
},
"keybinds": {
"type": "object",
"properties": {
"leader": {
"type": "string",
"default": "ctrl+x",
"description": "Leader key for keybind combinations\n\ndefault: `ctrl+x`",
"examples": [
"ctrl+x"
]
},
"app_help": {
"type": "string",
"default": "<leader>h",
"description": "Show help dialog\n\ndefault: `<leader>h`",
"examples": [
"<leader>h"
]
},
"editor_open": {
"type": "string",
"default": "<leader>e",
"description": "Open external editor\n\ndefault: `<leader>e`",
"examples": [
"<leader>e"
]
},
"session_new": {
"type": "string",
"default": "<leader>n",
"description": "Create a new session\n\ndefault: `<leader>n`",
"examples": [
"<leader>n"
]
},
"session_list": {
"type": "string",
"default": "<leader>l",
"description": "List all sessions\n\ndefault: `<leader>l`",
"examples": [
"<leader>l"
]
},
"session_share": {
"type": "string",
"default": "<leader>s",
"description": "Share current session\n\ndefault: `<leader>s`",
"examples": [
"<leader>s"
]
},
"session_unshare": {
"type": "string",
"default": "<leader>u",
"description": "Unshare current session\n\ndefault: `<leader>u`",
"examples": [
"<leader>u"
]
},
"session_interrupt": {
"type": "string",
"default": "esc",
"description": "Interrupt current session\n\ndefault: `esc`",
"examples": [
"esc"
]
},
"session_compact": {
"type": "string",
"default": "<leader>c",
"description": "Compact the session\n\ndefault: `<leader>c`",
"examples": [
"<leader>c"
]
},
"tool_details": {
"type": "string",
"default": "<leader>d",
"description": "Toggle tool details\n\ndefault: `<leader>d`",
"examples": [
"<leader>d"
]
},
"model_list": {
"type": "string",
"default": "<leader>m",
"description": "List available models\n\ndefault: `<leader>m`",
"examples": [
"<leader>m"
]
},
"theme_list": {
"type": "string",
"default": "<leader>t",
"description": "List available themes\n\ndefault: `<leader>t`",
"examples": [
"<leader>t"
]
},
"file_list": {
"type": "string",
"default": "<leader>f",
"description": "List files\n\ndefault: `<leader>f`",
"examples": [
"<leader>f"
]
},
"file_close": {
"type": "string",
"default": "esc",
"description": "Close file\n\ndefault: `esc`",
"examples": [
"esc"
]
},
"file_search": {
"type": "string",
"default": "<leader>/",
"description": "Search file\n\ndefault: `<leader>/`",
"examples": [
"<leader>/"
]
},
"file_diff_toggle": {
"type": "string",
"default": "<leader>v",
"description": "Split/unified diff\n\ndefault: `<leader>v`",
"examples": [
"<leader>v"
]
},
"project_init": {
"type": "string",
"default": "<leader>i",
"description": "Create/update AGENTS.md\n\ndefault: `<leader>i`",
"examples": [
"<leader>i"
]
},
"input_clear": {
"type": "string",
"default": "ctrl+c",
"description": "Clear input field\n\ndefault: `ctrl+c`",
"examples": [
"ctrl+c"
]
},
"input_paste": {
"type": "string",
"default": "ctrl+v",
"description": "Paste from clipboard\n\ndefault: `ctrl+v`",
"examples": [
"ctrl+v"
]
},
"input_submit": {
"type": "string",
"default": "enter",
"description": "Submit input\n\ndefault: `enter`",
"examples": [
"enter"
]
},
"input_newline": {
"type": "string",
"default": "shift+enter,ctrl+j",
"description": "Insert newline in input\n\ndefault: `shift+enter,ctrl+j`",
"examples": [
"shift+enter,ctrl+j"
]
},
"messages_page_up": {
"type": "string",
"default": "pgup",
"description": "Scroll messages up by one page\n\ndefault: `pgup`",
"examples": [
"pgup"
]
},
"messages_page_down": {
"type": "string",
"default": "pgdown",
"description": "Scroll messages down by one page\n\ndefault: `pgdown`",
"examples": [
"pgdown"
]
},
"messages_half_page_up": {
"type": "string",
"default": "ctrl+alt+u",
"description": "Scroll messages up by half page\n\ndefault: `ctrl+alt+u`",
"examples": [
"ctrl+alt+u"
]
},
"messages_half_page_down": {
"type": "string",
"default": "ctrl+alt+d",
"description": "Scroll messages down by half page\n\ndefault: `ctrl+alt+d`",
"examples": [
"ctrl+alt+d"
]
},
"messages_previous": {
"type": "string",
"default": "ctrl+up",
"description": "Navigate to previous message\n\ndefault: `ctrl+up`",
"examples": [
"ctrl+up"
]
},
"messages_next": {
"type": "string",
"default": "ctrl+down",
"description": "Navigate to next message\n\ndefault: `ctrl+down`",
"examples": [
"ctrl+down"
]
},
"messages_first": {
"type": "string",
"default": "ctrl+g",
"description": "Navigate to first message\n\ndefault: `ctrl+g`",
"examples": [
"ctrl+g"
]
},
"messages_last": {
"type": "string",
"default": "ctrl+alt+g",
"description": "Navigate to last message\n\ndefault: `ctrl+alt+g`",
"examples": [
"ctrl+alt+g"
]
},
"messages_layout_toggle": {
"type": "string",
"default": "<leader>p",
"description": "Toggle layout\n\ndefault: `<leader>p`",
"examples": [
"<leader>p"
]
},
"messages_copy": {
"type": "string",
"default": "<leader>y",
"description": "Copy message\n\ndefault: `<leader>y`",
"examples": [
"<leader>y"
]
},
"messages_revert": {
"type": "string",
"default": "<leader>r",
"description": "Revert message\n\ndefault: `<leader>r`",
"examples": [
"<leader>r"
]
},
"app_exit": {
"type": "string",
"default": "ctrl+c,<leader>q",
"description": "Exit the application\n\ndefault: `ctrl+c,<leader>q`",
"examples": [
"ctrl+c,<leader>q"
]
}
},
"additionalProperties": false,
"description": "Custom keybind configurations"
},
"autoshare": {
"type": "boolean",
"description": "Share newly created sessions automatically"
},
"autoupdate": {
"type": "boolean",
"description": "Automatically update to the latest version"
},
"disabled_providers": {
"type": "array",
"items": {
"type": "string"
},
"description": "Disable providers that are loaded automatically"
},
"model": {
"type": "string",
"description": "Model to use in the format of provider/model, eg anthropic/claude-2"
},
"provider": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"api": {
"type": "string"
},
"name": {
"type": "string"
},
"env": {
"type": "array",
"items": {
"type": "string"
}
},
"id": {
"type": "string"
},
"npm": {
"type": "string"
},
"models": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"release_date": {
"type": "string"
},
"attachment": {
"type": "boolean"
},
"reasoning": {
"type": "boolean"
},
"temperature": {
"type": "boolean"
},
"tool_call": {
"type": "boolean"
},
"cost": {
"type": "object",
"properties": {
"input": {
"type": "number"
},
"output": {
"type": "number"
},
"cache_read": {
"type": "number"
},
"cache_write": {
"type": "number"
}
},
"required": [
"input",
"output"
],
"additionalProperties": false
},
"limit": {
"type": "object",
"properties": {
"context": {
"type": "number"
},
"output": {
"type": "number"
}
},
"required": [
"context",
"output"
],
"additionalProperties": false
},
"options": {
"type": "object",
"additionalProperties": {}
}
},
"additionalProperties": false
}
},
"options": {
"type": "object",
"additionalProperties": {}
}
},
"required": [
"models"
],
"additionalProperties": false
},
"description": "Custom provider configurations and model overrides"
},
"mcp": {
"type": "object",
"additionalProperties": {
"anyOf": [
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "local",
"description": "Type of MCP server connection"
},
"command": {
"type": "array",
"items": {
"type": "string"
},
"description": "Command and arguments to run the MCP server"
},
"environment": {
"type": "object",
"additionalProperties": {
"type": "string"
},
"description": "Environment variables to set when running the MCP server"
},
"enabled": {
"type": "boolean",
"description": "Enable or disable the MCP server on startup"
}
},
"required": [
"type",
"command"
],
"additionalProperties": false
},
{
"type": "object",
"properties": {
"type": {
"type": "string",
"const": "remote",
"description": "Type of MCP server connection"
},
"url": {
"type": "string",
"description": "URL of the remote MCP server"
},
"enabled": {
"type": "boolean",
"description": "Enable or disable the MCP server on startup"
}
},
"required": [
"type",
"url"
],
"additionalProperties": false
}
]
},
"description": "MCP (Model Context Protocol) server configurations"
},
"instructions": {
"type": "array",
"items": {
"type": "string"
},
"description": "Additional instruction files or patterns to include"
},
"experimental": {
"type": "object",
"properties": {
"hook": {
"type": "object",
"properties": {
"file_edited": {
"type": "object",
"additionalProperties": {
"type": "array",
"items": {
"type": "object",
"properties": {
"command": {
"type": "array",
"items": {
"type": "string"
}
},
"environment": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"required": [
"command"
],
"additionalProperties": false
}
}
},
"session_completed": {
"type": "array",
"items": {
"type": "object",
"properties": {
"command": {
"type": "array",
"items": {
"type": "string"
}
},
"environment": {
"type": "object",
"additionalProperties": {
"type": "string"
}
}
},
"required": [
"command"
],
"additionalProperties": false
}
}
},
"additionalProperties": false
}
},
"additionalProperties": false
}
},
"additionalProperties": false,
"$schema": "http://json-schema.org/draft-07/schema#"
}
+1
View File
@@ -103,6 +103,7 @@ if (!snapshot) {
const lower = x.toLowerCase()
return (
!lower.includes("ignore:") &&
!lower.includes("chore:") &&
!lower.includes("ci:") &&
!lower.includes("wip:") &&
!lower.includes("docs:") &&
+3 -1
View File
@@ -4,6 +4,8 @@ import "zod-openapi/extend"
import { Config } from "../src/config/config"
import { zodToJsonSchema } from "zod-to-json-schema"
const file = process.argv[2]
const result = zodToJsonSchema(Config.Info, {
/**
* We'll use the `default` values of the field as the only value in `examples`.
@@ -30,4 +32,4 @@ const result = zodToJsonSchema(Config.Info, {
return jsonSchema
},
})
await Bun.write("config.schema.json", JSON.stringify(result, null, 2))
await Bun.write(file, JSON.stringify(result, null, 2))
+20
View File
@@ -55,6 +55,17 @@ export namespace Config {
export const Mcp = z.discriminatedUnion("type", [McpLocal, McpRemote])
export type Mcp = z.infer<typeof Mcp>
export const Mode = z
.object({
model: z.string().optional(),
prompt: z.string().optional(),
tools: z.record(z.string(), z.boolean()).optional(),
})
.openapi({
ref: "ModeConfig",
})
export type Mode = z.infer<typeof Mode>
export const Keybinds = z
.object({
leader: z.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),
@@ -99,6 +110,7 @@ export namespace Config {
.openapi({
ref: "KeybindsConfig",
})
export const Info = z
.object({
$schema: z.string().optional().describe("JSON schema reference for configuration validation"),
@@ -108,6 +120,14 @@ export namespace Config {
autoupdate: z.boolean().optional().describe("Automatically update to the latest version"),
disabled_providers: z.array(z.string()).optional().describe("Disable providers that are loaded automatically"),
model: z.string().describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(),
mode: z
.object({
build: Mode.optional(),
plan: Mode.optional(),
})
.catchall(Mode)
.optional(),
log_level: Log.Level.optional().describe("Minimum log level to write to log files"),
provider: z
.record(
ModelsDev.Provider.partial().extend({
+18 -5
View File
@@ -11,6 +11,19 @@ import { Log } from "../util/log"
export namespace File {
const log = Log.create({ service: "file" })
export const Info = z
.object({
path: z.string(),
added: z.number().int(),
removed: z.number().int(),
status: z.enum(["added", "deleted", "modified"]),
})
.openapi({
ref: "File",
})
export type Info = z.infer<typeof Info>
export const Event = {
Edited: Bus.event(
"file.edited",
@@ -26,14 +39,14 @@ export namespace File {
const diffOutput = await $`git diff --numstat HEAD`.cwd(app.path.cwd).quiet().nothrow().text()
const changedFiles = []
const changedFiles: Info[] = []
if (diffOutput.trim()) {
const lines = diffOutput.trim().split("\n")
for (const line of lines) {
const [added, removed, filepath] = line.split("\t")
changedFiles.push({
file: filepath,
path: filepath,
added: added === "-" ? 0 : parseInt(added, 10),
removed: removed === "-" ? 0 : parseInt(removed, 10),
status: "modified",
@@ -50,7 +63,7 @@ export namespace File {
const content = await Bun.file(path.join(app.path.root, filepath)).text()
const lines = content.split("\n").length
changedFiles.push({
file: filepath,
path: filepath,
added: lines,
removed: 0,
status: "added",
@@ -68,7 +81,7 @@ export namespace File {
const deletedFiles = deletedOutput.trim().split("\n")
for (const filepath of deletedFiles) {
changedFiles.push({
file: filepath,
path: filepath,
added: 0,
removed: 0, // Could get original line count but would require another git command
status: "deleted",
@@ -78,7 +91,7 @@ export namespace File {
return changedFiles.map((x) => ({
...x,
file: path.relative(app.path.cwd, path.join(app.path.root, x.file)),
path: path.relative(app.path.cwd, path.join(app.path.root, x.path)),
}))
}
+20 -18
View File
@@ -34,25 +34,27 @@ export namespace Ripgrep {
export const Match = z.object({
type: z.literal("match"),
data: z.object({
path: z.object({
text: z.string(),
}),
lines: z.object({
text: z.string(),
}),
line_number: z.number(),
absolute_offset: z.number(),
submatches: z.array(
z.object({
match: z.object({
text: z.string(),
}),
start: z.number(),
end: z.number(),
data: z
.object({
path: z.object({
text: z.string(),
}),
),
}),
lines: z.object({
text: z.string(),
}),
line_number: z.number(),
absolute_offset: z.number(),
submatches: z.array(
z.object({
match: z.object({
text: z.string(),
}),
start: z.number(),
end: z.number(),
}),
),
})
.openapi({ ref: "Match" }),
})
const End = z.object({
+8 -17
View File
@@ -1,5 +1,7 @@
import { App } from "../app/app"
import { BunProc } from "../bun"
import { Filesystem } from "../util/filesystem"
import path from "path"
export interface Info {
name: string
@@ -29,7 +31,7 @@ export const mix: Info = {
export const prettier: Info = {
name: "prettier",
command: [BunProc.which(), "run", "prettier", "--write", "$FILE"],
command: [BunProc.which(), "x", "prettier", "--write", "$FILE"],
environment: {
BUN_BE_BUN: "1",
},
@@ -62,23 +64,12 @@ export const prettier: Info = {
".gql",
],
async enabled() {
// this is more complicated because we only want to use prettier if it's
// being used with the current project
try {
const proc = Bun.spawn({
cmd: [BunProc.which(), "run", "prettier", "--version"],
cwd: App.info().path.cwd,
env: {
BUN_BE_BUN: "1",
},
stdout: "ignore",
stderr: "ignore",
})
const exit = await proc.exited
return exit === 0
} catch {
return false
const app = App.info()
const nms = await Filesystem.findUp("node_modules", app.path.cwd, app.path.root)
for (const item of nms) {
if (await Bun.file(path.join(item, ".bin", "prettier")).exists()) return true
}
return false
},
}
+18
View File
@@ -40,6 +40,24 @@ const cli = yargs(hideBin(process.argv))
})
.middleware(async () => {
await Log.init({ print: process.argv.includes("--print-logs") })
try {
const { Config } = await import("./config/config")
const { App } = await import("./app/app")
App.provide({ cwd: process.cwd() }, async () => {
const cfg = await Config.get()
if (cfg.log_level) {
Log.setLevel(cfg.log_level as Log.Level)
} else {
const defaultLevel = Installation.isDev() ? "DEBUG" : "INFO"
Log.setLevel(defaultLevel)
}
})
} catch (e) {
Log.Default.error("failed to load config", { error: e })
}
Log.Default.info("opencode", {
version: Installation.VERSION,
args: process.argv.slice(2),
+1 -3
View File
@@ -184,9 +184,7 @@ export namespace LSPClient {
},
}
if (input.server.onInitialized) {
await input.server.onInitialized(result)
}
if (input.server.onInitialized) input.server.onInitialized(result)
l.info("initialized")
return result
+1 -1
View File
@@ -28,7 +28,7 @@ export namespace LSP {
}),
})
.openapi({
ref: "LSP.Symbol",
ref: "Symbol",
})
export type Symbol = z.infer<typeof Symbol>
+112 -4
View File
@@ -24,9 +24,8 @@ export namespace LSPServer {
const SimpleRoots = (patterns: string[]): RootsFunction => {
return async (app) => {
const glob = `**/*/{${patterns.join(",")}}`
const files = await Ripgrep.files({
glob: [glob],
glob: patterns.map((p) => `**/${p}`),
cwd: app.path.root,
})
const dirs = files.map((file) => path.dirname(file))
@@ -44,7 +43,7 @@ export namespace LSPServer {
export const Typescript: Info = {
id: "typescript",
roots: SimpleRoots(["tsconfig.json", "jsconfig.json", "package.json"]),
roots: async (app) => [app.path.root],
extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"],
async spawn(app, root) {
const tsserver = await Bun.resolve("typescript/lib/tsserver.js", app.path.cwd).catch(() => {})
@@ -86,7 +85,11 @@ export namespace LSPServer {
export const Gopls: Info = {
id: "golang",
roots: SimpleRoots(["go.mod", "go.sum"]),
roots: async (app) => {
const work = await SimpleRoots(["go.work"])(app)
if (work.length > 0) return work
return SimpleRoots(["go.mod", "go.sum"])(app)
},
extensions: [".go"],
async spawn(_, root) {
let bin = Bun.which("gopls", {
@@ -239,4 +242,109 @@ export namespace LSPServer {
}
},
}
export const Zls: Info = {
id: "zls",
extensions: [".zig", ".zon"],
roots: SimpleRoots(["build.zig"]),
async spawn(_, root) {
let bin = Bun.which("zls", {
PATH: process.env["PATH"] + ":" + Global.Path.bin,
})
if (!bin) {
const zig = Bun.which("zig")
if (!zig) {
log.error("Zig is required to use zls. Please install Zig first.")
return
}
log.info("downloading zls from GitHub releases")
const releaseResponse = await fetch("https://api.github.com/repos/zigtools/zls/releases/latest")
if (!releaseResponse.ok) {
log.error("Failed to fetch zls release info")
return
}
const release = await releaseResponse.json()
const platform = process.platform
const arch = process.arch
let assetName = ""
let zlsArch: string = arch
if (arch === "arm64") zlsArch = "aarch64"
else if (arch === "x64") zlsArch = "x86_64"
else if (arch === "ia32") zlsArch = "x86"
let zlsPlatform: string = platform
if (platform === "darwin") zlsPlatform = "macos"
else if (platform === "win32") zlsPlatform = "windows"
const ext = platform === "win32" ? "zip" : "tar.xz"
assetName = `zls-${zlsArch}-${zlsPlatform}.${ext}`
const supportedCombos = [
"zls-x86_64-linux.tar.xz",
"zls-x86_64-macos.tar.xz",
"zls-x86_64-windows.zip",
"zls-aarch64-linux.tar.xz",
"zls-aarch64-macos.tar.xz",
"zls-aarch64-windows.zip",
"zls-x86-linux.tar.xz",
"zls-x86-windows.zip",
]
if (!supportedCombos.includes(assetName)) {
log.error(`Platform ${platform} and architecture ${arch} is not supported by zls`)
return
}
const asset = release.assets.find((a: any) => a.name === assetName)
if (!asset) {
log.error(`Could not find asset ${assetName} in latest zls release`)
return
}
const downloadUrl = asset.browser_download_url
const downloadResponse = await fetch(downloadUrl)
if (!downloadResponse.ok) {
log.error("Failed to download zls")
return
}
const tempPath = path.join(Global.Path.bin, assetName)
await Bun.file(tempPath).write(downloadResponse)
if (ext === "zip") {
await $`unzip -o -q ${tempPath}`.cwd(Global.Path.bin).nothrow()
} else {
await $`tar -xf ${tempPath}`.cwd(Global.Path.bin).nothrow()
}
await fs.rm(tempPath, { force: true })
bin = path.join(Global.Path.bin, "zls" + (platform === "win32" ? ".exe" : ""))
if (!(await Bun.file(bin).exists())) {
log.error("Failed to extract zls binary")
return
}
if (platform !== "win32") {
await $`chmod +x ${bin}`.nothrow()
}
log.info(`installed zls`, { bin })
}
return {
process: spawn(bin, {
cwd: root,
}),
}
},
}
}
+72 -11
View File
@@ -16,6 +16,7 @@ import { Config } from "../config/config"
import { File } from "../file"
import { LSP } from "../lsp"
import { MessageV2 } from "../session/message-v2"
import { Mode } from "../session/mode"
const ERRORS = {
400: {
@@ -558,7 +559,7 @@ export namespace Server {
description: "Symbols",
content: {
"application/json": {
schema: resolver(z.unknown().array()),
schema: resolver(LSP.Symbol.array()),
},
},
},
@@ -621,16 +622,7 @@ export namespace Server {
description: "File status",
content: {
"application/json": {
schema: resolver(
z
.object({
file: z.string(),
added: z.number().int(),
removed: z.number().int(),
status: z.enum(["added", "deleted", "modified"]),
})
.array(),
),
schema: resolver(File.Info.array()),
},
},
},
@@ -641,6 +633,75 @@ export namespace Server {
return c.json(content)
},
)
.post(
"/log",
describeRoute({
description: "Write a log entry to the server logs",
responses: {
200: {
description: "Log entry written successfully",
content: {
"application/json": {
schema: resolver(z.boolean()),
},
},
},
},
}),
zValidator(
"json",
z.object({
service: z.string().openapi({ description: "Service name for the log entry" }),
level: z.enum(["debug", "info", "error", "warn"]).openapi({ description: "Log level" }),
message: z.string().openapi({ description: "Log message" }),
extra: z
.record(z.string(), z.any())
.optional()
.openapi({ description: "Additional metadata for the log entry" }),
}),
),
async (c) => {
const { service, level, message, extra } = c.req.valid("json")
const logger = Log.create({ service })
switch (level) {
case "debug":
logger.debug(message, extra)
break
case "info":
logger.info(message, extra)
break
case "error":
logger.error(message, extra)
break
case "warn":
logger.warn(message, extra)
break
}
return c.json(true)
},
)
.get(
"/mode",
describeRoute({
description: "List all modes",
responses: {
200: {
description: "List of modes",
content: {
"application/json": {
schema: resolver(Mode.Info.array()),
},
},
},
},
}),
async (c) => {
const modes = await Mode.list()
return c.json(modes)
},
)
return result
}
+22 -5
View File
@@ -15,6 +15,7 @@ import {
} 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"
@@ -29,12 +30,12 @@ import type { ModelsDev } from "../provider/models"
import { Share } from "../share/share"
import { Snapshot } from "../snapshot"
import { Storage } from "../storage/storage"
import type { Tool } from "../tool/tool"
import { Log } from "../util/log"
import { NamedError } from "../util/error"
import { SystemPrompt } from "./system"
import { FileTime } from "../file/time"
import { MessageV2 } from "./message-v2"
import { Mode } from "./mode"
export namespace Session {
const log = Log.create({ service: "session" })
@@ -281,13 +282,13 @@ export namespace Session {
sessionID: string
providerID: string
modelID: string
mode?: string
parts: MessageV2.UserPart[]
system?: string[]
tools?: Tool.Info[]
}) {
using abort = lock(input.sessionID)
const l = log.clone().tag("session", input.sessionID)
l.info("chatting")
const model = await Provider.getModel(input.providerID, input.modelID)
let msgs = await messages(input.sessionID)
const session = await get(input.sessionID)
@@ -364,6 +365,7 @@ export namespace Session {
return [
{
type: "text",
synthetic: true,
text: ["Called the Read tool on " + url.pathname, "<results>", text, "</results>"].join("\n"),
},
]
@@ -373,6 +375,7 @@ export namespace Session {
{
type: "text",
text: `Called the Read tool with the following input: {\"filePath\":\"${url.pathname}\"}`,
synthetic: true,
},
{
type: "file",
@@ -386,6 +389,14 @@ export namespace Session {
return [part]
}),
).then((x) => x.flat())
if (input.mode === "plan")
input.parts.push({
type: "text",
text: PROMPT_PLAN,
synthetic: true,
})
if (msgs.length === 0 && !session.parentID) {
generateText({
maxOutputTokens: input.providerID === "google" ? 1024 : 20,
@@ -431,9 +442,13 @@ export namespace Session {
await updateMessage(msg)
msgs.push(msg)
const system = input.system ?? SystemPrompt.provider(input.providerID)
const mode = await Mode.get(input.mode ?? "build")
let system = mode.prompt ? [mode.prompt] : SystemPrompt.provider(input.providerID, input.modelID)
system.push(...(await SystemPrompt.environment()))
system.push(...(await SystemPrompt.custom()))
// max 2 system prompt messages for caching purposes
const [first, ...rest] = system
system = [first, rest.join("\n")]
const next: MessageV2.Info = {
id: Identifier.ascending("message"),
@@ -462,7 +477,8 @@ export namespace Session {
const tools: Record<string, AITool> = {}
for (const item of await Provider.tools(input.providerID)) {
tools[item.id.replaceAll(".", "_")] = tool({
if (mode.tools[item.id] === false) continue
tools[item.id] = tool({
id: item.id as any,
description: item.description,
inputSchema: item.parameters as ZodSchema,
@@ -494,6 +510,7 @@ export namespace Session {
}
for (const [key, item] of Object.entries(await MCP.tools())) {
if (mode.tools[key] === false) continue
const execute = item.execute
if (!execute) continue
item.execute = async (args, opts) => {
@@ -76,6 +76,7 @@ export namespace MessageV2 {
.object({
type: z.literal("text"),
text: z.string(),
synthetic: z.boolean().optional(),
})
.openapi({
ref: "TextPart",
+69
View File
@@ -0,0 +1,69 @@
import { mergeDeep } from "remeda"
import { App } from "../app/app"
import { Config } from "../config/config"
import z from "zod"
export namespace Mode {
export const Info = z
.object({
name: z.string(),
model: z
.object({
modelID: z.string(),
providerID: z.string(),
})
.optional(),
prompt: z.string().optional(),
tools: z.record(z.boolean()),
})
.openapi({
ref: "Mode",
})
export type Info = z.infer<typeof Info>
const state = App.state("mode", async () => {
const cfg = await Config.get()
const mode = mergeDeep(
{
build: {},
plan: {
tools: {
write: false,
edit: false,
patch: false,
},
},
},
cfg.mode ?? {},
)
const result: Record<string, Info> = {}
for (const [key, value] of Object.entries(mode)) {
let item = result[key]
if (!item)
item = result[key] = {
name: key,
tools: {},
}
const model = value.model ?? cfg.model
if (model) {
const [providerID, ...rest] = model.split("/")
const modelID = rest.join("/")
item.model = {
modelID,
providerID,
}
}
if (value.prompt) item.prompt = await Bun.file(value.prompt).text()
if (value.tools) item.tools = value.tools
}
return result
})
export async function get(mode: string) {
return state().then((x) => x[mode])
}
export async function list() {
return state().then((x) => Object.values(x))
}
}
@@ -0,0 +1,95 @@
You are an agent known as opencode - please keep going until the users query is completely resolved, before ending your turn and yielding back to the user.
Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough.
You MUST iterate and keep going until the problem is solved.
I want you to fully solve this autonomously before coming back to me.
Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.
Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why.
If the user request is "resume" or "continue" or "try again", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is.
Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
# Workflow
1. Understand the problem deeply. Carefully read the issue and think critically about what is required.
2. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
3. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps. Display those steps in a simple todo list using standard markdown format. Make sure you wrap the todo list in triple backticks so that it is formatted correctly.
4. Implement the fix incrementally. Make small, testable code changes.
5. Debug as needed. Use debugging techniques to isolate and resolve issues.
6. Test frequently. Run tests after each change to verify correctness.
7. Iterate until the root cause is fixed and all tests pass.
8. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.
Refer to the detailed sections below for more information on each step.
## 1. Deeply Understand the Problem
Carefully read the issue and think hard about a plan to solve it before coding.
## 2. Codebase Investigation
- Explore relevant files and directories.
- Search for key functions, classes, or variables related to the issue.
- Read and understand relevant code snippets.
- Identify the root cause of the problem.
- Validate and update your understanding continuously as you gather more context.
## 3. Fetch Provided URLs
- If the user provides a URL, use the `functions.fetch_webpage` tool to retrieve the content of the provided URL.
- After fetching, review the content returned by the fetch tool.
- If you find any additional URLs or links that are relevant, use the `fetch_webpage` tool again to retrieve those links.
- Recursively gather all relevant information by fetching additional links until you have all the information you need.
## 4. Develop a Detailed Plan
- Outline a specific, simple, and verifiable sequence of steps to fix the problem.
- Create a todo list in markdown format to track your progress.
- Each time you complete a step, check it off using `[x]` syntax.
- Each time you check off a step, display the updated todo list to the user.
- Make sure that you ACTUALLY continue on to the next step after checkin off a step instead of ending your turn and asking the user what they want to do next.
## 5. Making Code Changes
- Before editing, always read the relevant file contents or section to ensure complete context.
- Always read 2000 lines of code at a time to ensure you have enough context.
- If a patch is not applied correctly, attempt to reapply it.
- Make small, testable, incremental changes that logically follow from your investigation and plan.
## 6. Debugging
- Make code changes only if you have high confidence they can solve the problem
- When debugging, try to determine the root cause rather than addressing symptoms
- Debug for as long as needed to identify the root cause and identify a fix
- Use the #problems tool to check for any problems in the code
- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening
- To test hypotheses, you can also add test statements or functions
- Revisit your assumptions if unexpected behavior occurs.
# Fetch Webpage
Use the `webfetch` tool when the user provides a URL. Follow these steps exactly.
1. Use the `webfetch` tool to retrieve the content of the provided URL.
2. After fetching, review the content returned by the fetch tool.
3. If you find any additional URLs or links that are relevant, use the `webfetch` tool again to retrieve those links.
4. Go back to step 2 and repeat until you have all the information you need.
IMPORTANT: Recursively fetching links is crucial. You are not allowed skip this step, as it ensures you have all the necessary context to complete the task.
# How to create a Todo List
Use the following format to create a todo list:
```markdown
- [ ] Step 1: Description of the first step
- [ ] Step 2: Description of the second step
- [ ] Step 3: Description of the third step
```
Do not ever use HTML tags or any other formatting for the todo list, as it will not be rendered correctly. Always use the markdown format shown above.
# Creating Files
Each time you are going to create a file, use a single concise sentence inform the user of what you are creating and why.
# Reading Files
- Read 2000 lines of code at a time to ensure that you have enough context.
- Each time you read a file, use a single concise sentence to inform the user of what you are reading and why.
@@ -0,0 +1,3 @@
<system-reminder>
Plan mode is active. The user indicated that they do not want you to execute yet -- you MUST NOT make any edits, run any non-readonly tools (including changing configs or making commits), or otherwise make any changes to the system. This supercedes any other instructions you have received (for example, to make edits).
</system-reminder>
+5 -12
View File
@@ -7,23 +7,16 @@ import path from "path"
import os from "os"
import PROMPT_ANTHROPIC from "./prompt/anthropic.txt"
import PROMPT_BEAST from "./prompt/beast.txt"
import PROMPT_ANTHROPIC_SPOOF from "./prompt/anthropic_spoof.txt"
import PROMPT_SUMMARIZE from "./prompt/summarize.txt"
import PROMPT_TITLE from "./prompt/title.txt"
export namespace SystemPrompt {
export function provider(providerID: string) {
const result = []
switch (providerID) {
case "anthropic":
result.push(PROMPT_ANTHROPIC_SPOOF.trim())
result.push(PROMPT_ANTHROPIC)
break
default:
result.push(PROMPT_ANTHROPIC)
break
}
return result
export function provider(providerID: string, modelID: string) {
if (providerID === "anthropic") return [PROMPT_ANTHROPIC_SPOOF.trim(), PROMPT_ANTHROPIC]
if (modelID.includes("gpt-")) return [PROMPT_BEAST]
return [PROMPT_ANTHROPIC]
}
export async function environment() {
+2
View File
@@ -16,6 +16,8 @@ export const IGNORE_PATTERNS = [
"obj/",
".idea/",
".vscode/",
".zig-cache/",
"zig-out",
]
const LIMIT = 100
+1 -1
View File
@@ -71,7 +71,7 @@ export const ReadTool = Tool.define({
output += "\n</file>"
// just warms the lsp client
await LSP.touchFile(filePath, false)
LSP.touchFile(filePath, false)
FileTime.read(ctx.sessionID, filePath)
return {
+72 -5
View File
@@ -1,15 +1,59 @@
import path from "path"
import fs from "fs/promises"
import { Global } from "../global"
import z from "zod"
export namespace Log {
export const Level = z.enum(["DEBUG", "INFO", "WARN", "ERROR"]).openapi({ ref: "LogLevel", description: "Log level" })
export type Level = z.infer<typeof Level>
const levelPriority: Record<Level, number> = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
}
let currentLevel: Level = "INFO"
export function setLevel(level: Level) {
currentLevel = level
}
export function getLevel(): Level {
return currentLevel
}
function shouldLog(level: Level): boolean {
return levelPriority[level] >= levelPriority[currentLevel]
}
export type Logger = {
debug(message?: any, extra?: Record<string, any>): void
info(message?: any, extra?: Record<string, any>): void
error(message?: any, extra?: Record<string, any>): void
warn(message?: any, extra?: Record<string, any>): void
tag(key: string, value: string): Logger
clone(): Logger
time(
message: string,
extra?: Record<string, any>,
): {
stop(): void
[Symbol.dispose](): void
}
}
const loggers = new Map<string, Logger>()
export const Default = create({ service: "default" })
export interface Options {
print: boolean
level?: Level
}
let logpath = ""
export function file() {
return logpath
}
@@ -47,6 +91,14 @@ export namespace Log {
export function create(tags?: Record<string, any>) {
tags = tags || {}
const service = tags["service"]
if (service && typeof service === "string") {
const cached = loggers.get(service)
if (cached) {
return cached
}
}
function build(message: any, extra?: Record<string, any>) {
const prefix = Object.entries({
...tags,
@@ -60,15 +112,26 @@ export namespace Log {
last = next.getTime()
return [next.toISOString().split(".")[0], "+" + diff + "ms", prefix, message].filter(Boolean).join(" ") + "\n"
}
const result = {
const result: Logger = {
debug(message?: any, extra?: Record<string, any>) {
if (shouldLog("DEBUG")) {
process.stderr.write("DEBUG " + build(message, extra))
}
},
info(message?: any, extra?: Record<string, any>) {
process.stderr.write("INFO " + build(message, extra))
if (shouldLog("INFO")) {
process.stderr.write("INFO " + build(message, extra))
}
},
error(message?: any, extra?: Record<string, any>) {
process.stderr.write("ERROR " + build(message, extra))
if (shouldLog("ERROR")) {
process.stderr.write("ERROR " + build(message, extra))
}
},
warn(message?: any, extra?: Record<string, any>) {
process.stderr.write("WARN " + build(message, extra))
if (shouldLog("WARN")) {
process.stderr.write("WARN " + build(message, extra))
}
},
tag(key: string, value: string) {
if (tags) tags[key] = value
@@ -96,6 +159,10 @@ export namespace Log {
},
}
if (service && typeof service === "string") {
loggers.set(service, result)
}
return result
}
}
-12
View File
@@ -1,12 +0,0 @@
# These are supported funding model platforms
github: [changkun] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
-71
View File
@@ -1,71 +0,0 @@
# Copyright 2021 The golang.design Initiative Authors.
# All rights reserved. Use of this source code is governed
# by a MIT license that can be found in the LICENSE file.
#
# Written by Changkun Ou <changkun.de>
name: clipboard
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
platform_test:
env:
DISPLAY: ':0.0'
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
go: ['1.24.x']
steps:
- name: Install and run dependencies (xvfb libx11-dev)
if: ${{ runner.os == 'Linux' }}
run: |
sudo apt update
sudo apt install -y xvfb libx11-dev x11-utils libegl1-mesa-dev libgles2-mesa-dev
Xvfb :0 -screen 0 1024x768x24 > /dev/null 2>&1 &
# Wait for Xvfb
MAX_ATTEMPTS=120 # About 60 seconds
COUNT=0
echo -n "Waiting for Xvfb to be ready..."
while ! xdpyinfo -display "${DISPLAY}" >/dev/null 2>&1; do
echo -n "."
sleep 0.50s
COUNT=$(( COUNT + 1 ))
if [ "${COUNT}" -ge "${MAX_ATTEMPTS}" ]; then
echo " Gave up waiting for X server on ${DISPLAY}"
exit 1
fi
done
echo "Done - Xvfb is ready!"
- uses: actions/checkout@v2
- uses: actions/setup-go@v2
with:
stable: 'false'
go-version: ${{ matrix.go }}
- name: Build (${{ matrix.go }})
run: |
go build -o gclip cmd/gclip/main.go
go build -o gclip-gui cmd/gclip-gui/main.go
- name: Run Tests with CGO_ENABLED=1 (${{ matrix.go }})
if: ${{ runner.os == 'Linux' || runner.os == 'macOS'}}
run: |
CGO_ENABLED=1 go test -v -covermode=atomic .
- name: Run Tests with CGO_ENABLED=0 (${{ matrix.go }})
if: ${{ runner.os == 'Linux' || runner.os == 'macOS'}}
run: |
CGO_ENABLED=0 go test -v -covermode=atomic .
- name: Run Tests on Windows (${{ matrix.go }})
if: ${{ runner.os == 'Windows'}}
run: |
go test -v -covermode=atomic .
-15
View File
@@ -1,15 +0,0 @@
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
-13
View File
@@ -1,13 +0,0 @@
# Copyright 2021 The golang.design Initiative Authors.
# All rights reserved. Use of this source code is governed
# by a MIT license that can be found in the LICENSE file.
#
# Written by Changkun Ou <changkun.de>
FROM golang:1.24
RUN apt-get update && apt-get install -y \
xvfb libx11-dev libegl1-mesa-dev libgles2-mesa-dev \
&& apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
WORKDIR /app
COPY . .
CMD [ "sh", "-c", "./tests/test-docker.sh" ]
-21
View File
@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2021 Changkun Ou <contact@changkun.de>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-162
View File
@@ -1,162 +0,0 @@
# clipboard [![PkgGoDev](https://pkg.go.dev/badge/golang.design/x/clipboard)](https://pkg.go.dev/golang.design/x/clipboard) ![](https://changkun.de/urlstat?mode=github&repo=golang-design/clipboard) ![clipboard](https://github.com/golang-design/clipboard/workflows/clipboard/badge.svg?branch=main)
Cross platform (macOS/Linux/Windows/Android/iOS) clipboard package in Go
```go
import "golang.design/x/clipboard"
```
## Features
- Cross platform supports: **macOS, Linux (X11), Windows, iOS, and Android**
- Copy/paste UTF-8 text
- Copy/paste PNG encoded images (Desktop-only)
- Command `gclip` as a demo application
- Mobile app `gclip-gui` as a demo application
## API Usage
Package clipboard provides cross platform clipboard access and supports
macOS/Linux/Windows/Android/iOS platform. Before interacting with the
clipboard, one must call Init to assert if it is possible to use this
package:
```go
// Init returns an error if the package is not ready for use.
err := clipboard.Init()
if err != nil {
panic(err)
}
```
The most common operations are `Read` and `Write`. To use them:
```go
// write/read text format data of the clipboard, and
// the byte buffer regarding the text are UTF8 encoded.
clipboard.Write(clipboard.FmtText, []byte("text data"))
clipboard.Read(clipboard.FmtText)
// write/read image format data of the clipboard, and
// the byte buffer regarding the image are PNG encoded.
clipboard.Write(clipboard.FmtImage, []byte("image data"))
clipboard.Read(clipboard.FmtImage)
```
Note that read/write regarding image format assumes that the bytes are
PNG encoded since it serves the alpha blending purpose that might be
used in other graphical software.
In addition, `clipboard.Write` returns a channel that can receive an
empty struct as a signal, which indicates the corresponding write call
to the clipboard is outdated, meaning the clipboard has been overwritten
by others and the previously written data is lost. For instance:
```go
changed := clipboard.Write(clipboard.FmtText, []byte("text data"))
select {
case <-changed:
println(`"text data" is no longer available from clipboard.`)
}
```
You can ignore the returning channel if you don't need this type of
notification. Furthermore, when you need more than just knowing whether
clipboard data is changed, use the watcher API:
```go
ch := clipboard.Watch(context.TODO(), clipboard.FmtText)
for data := range ch {
// print out clipboard data whenever it is changed
println(string(data))
}
```
## Demos
- A command line tool `gclip` for command line clipboard accesses, see document [here](./cmd/gclip/README.md).
- A GUI application `gclip-gui` for functionality verifications on mobile systems, see a document [here](./cmd/gclip-gui/README.md).
## Command Usage
`gclip` command offers the ability to interact with the system clipboard
from the shell. To install:
```bash
$ go install golang.design/x/clipboard/cmd/gclip@latest
```
```bash
$ gclip
gclip is a command that provides clipboard interaction.
usage: gclip [-copy|-paste] [-f <file>]
options:
-copy
copy data to clipboard
-f string
source or destination to a given file path
-paste
paste data from clipboard
examples:
gclip -paste paste from clipboard and prints the content
gclip -paste -f x.txt paste from clipboard and save as text to x.txt
gclip -paste -f x.png paste from clipboard and save as image to x.png
cat x.txt | gclip -copy copy content from x.txt to clipboard
gclip -copy -f x.txt copy content from x.txt to clipboard
gclip -copy -f x.png copy x.png as image data to clipboard
```
If `-copy` is used, the command will exit when the data is no longer
available from the clipboard. You can always send the command to the
background using a shell `&` operator, for example:
```bash
$ cat x.txt | gclip -copy &
```
## Platform Specific Details
This package spent efforts to provide cross platform abstraction regarding
accessing system clipboards, but here are a few details you might need to know.
### Dependency
- macOS: require Cgo, no dependency
- Linux: require X11 dev package. For instance, install `libx11-dev` or `xorg-dev` or `libX11-devel` to access X window system.
Wayland sessions are currently unsupported; running under Wayland
typically requires an XWayland bridge and `DISPLAY` to be set.
- Windows: no Cgo, no dependency
- iOS/Android: collaborate with [`gomobile`](https://golang.org/x/mobile)
### Screenshot
In general, when you need test your implementation regarding images,
There are system level shortcuts to put screenshot image into your system clipboard:
- On macOS, use `Ctrl+Shift+Cmd+4`
- On Linux/Ubuntu, use `Ctrl+Shift+PrintScreen`
- On Windows, use `Shift+Win+s`
As described in the API documentation, the package supports read/write
UTF8 encoded plain text or PNG encoded image data. Thus,
the other types of data are not supported yet, i.e. undefined behavior.
## Who is using this package?
The main purpose of building this package is to support the
[midgard](https://changkun.de/s/midgard) project, which offers
clipboard-based features like universal clipboard service that syncs
clipboard content across multiple systems, allocating public accessible
for clipboard content, etc.
To know more projects, check our [wiki](https://github.com/golang-design/clipboard/wiki) page.
## License
MIT | &copy; 2021 The golang.design Initiative Authors, written by [Changkun Ou](https://changkun.de).
@@ -1,80 +0,0 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build android
#include <android/log.h>
#include <jni.h>
#include <stdlib.h>
#include <string.h>
#define LOG_FATAL(...) __android_log_print(ANDROID_LOG_FATAL, \
"GOLANG.DESIGN/X/CLIPBOARD", __VA_ARGS__)
static jmethodID find_method(JNIEnv *env, jclass clazz, const char *name, const char *sig) {
jmethodID m = (*env)->GetMethodID(env, clazz, name, sig);
if (m == 0) {
(*env)->ExceptionClear(env);
LOG_FATAL("cannot find method %s %s", name, sig);
return 0;
}
return m;
}
jobject get_clipboard(uintptr_t jni_env, uintptr_t ctx) {
JNIEnv *env = (JNIEnv*)jni_env;
jclass ctxClass = (*env)->GetObjectClass(env, (jobject)ctx);
jmethodID getSystemService = find_method(env, ctxClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
jstring service = (*env)->NewStringUTF(env, "clipboard");
jobject ret = (jobject)(*env)->CallObjectMethod(env, (jobject)ctx, getSystemService, service);
jthrowable err = (*env)->ExceptionOccurred(env);
if (err != NULL) {
LOG_FATAL("cannot find clipboard");
(*env)->ExceptionClear(env);
return NULL;
}
return ret;
}
char *clipboard_read_string(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx) {
JNIEnv *env = (JNIEnv*)jni_env;
jobject mgr = get_clipboard(jni_env, ctx);
if (mgr == NULL) {
return NULL;
}
jclass mgrClass = (*env)->GetObjectClass(env, mgr);
jmethodID getText = find_method(env, mgrClass, "getText", "()Ljava/lang/CharSequence;");
jobject content = (jstring)(*env)->CallObjectMethod(env, mgr, getText);
if (content == NULL) {
return NULL;
}
jclass clzCharSequence = (*env)->GetObjectClass(env, content);
jmethodID toString = (*env)->GetMethodID(env, clzCharSequence, "toString", "()Ljava/lang/String;");
jobject s = (*env)->CallObjectMethod(env, content, toString);
const char *chars = (*env)->GetStringUTFChars(env, s, NULL);
char *copy = strdup(chars);
(*env)->ReleaseStringUTFChars(env, s, chars);
return copy;
}
void clipboard_write_string(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx, char *str) {
JNIEnv *env = (JNIEnv*)jni_env;
jobject mgr = get_clipboard(jni_env, ctx);
if (mgr == NULL) {
return;
}
jclass mgrClass = (*env)->GetObjectClass(env, mgr);
jmethodID setText = find_method(env, mgrClass, "setText", "(Ljava/lang/CharSequence;)V");
(*env)->CallVoidMethod(env, mgr, setText, (*env)->NewStringUTF(env, str));
}
-102
View File
@@ -1,102 +0,0 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build android
package clipboard
/*
#cgo LDFLAGS: -landroid -llog
#include <stdlib.h>
char *clipboard_read_string(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx);
void clipboard_write_string(uintptr_t java_vm, uintptr_t jni_env, uintptr_t ctx, char *str);
*/
import "C"
import (
"bytes"
"context"
"time"
"unsafe"
"golang.org/x/mobile/app"
)
func initialize() error { return nil }
func read(t Format) (buf []byte, err error) {
switch t {
case FmtText:
s := ""
if err := app.RunOnJVM(func(vm, env, ctx uintptr) error {
cs := C.clipboard_read_string(C.uintptr_t(vm), C.uintptr_t(env), C.uintptr_t(ctx))
if cs == nil {
return nil
}
s = C.GoString(cs)
C.free(unsafe.Pointer(cs))
return nil
}); err != nil {
return nil, err
}
return []byte(s), nil
case FmtImage:
return nil, errUnsupported
default:
return nil, errUnsupported
}
}
// write writes the given data to clipboard and
// returns true if success or false if failed.
func write(t Format, buf []byte) (<-chan struct{}, error) {
done := make(chan struct{}, 1)
switch t {
case FmtText:
cs := C.CString(string(buf))
defer C.free(unsafe.Pointer(cs))
if err := app.RunOnJVM(func(vm, env, ctx uintptr) error {
C.clipboard_write_string(C.uintptr_t(vm), C.uintptr_t(env), C.uintptr_t(ctx), cs)
done <- struct{}{}
return nil
}); err != nil {
return nil, err
}
return done, nil
case FmtImage:
return nil, errUnsupported
default:
return nil, errUnsupported
}
}
func watch(ctx context.Context, t Format) <-chan []byte {
recv := make(chan []byte, 1)
ti := time.NewTicker(time.Second)
last := Read(t)
go func() {
for {
select {
case <-ctx.Done():
close(recv)
return
case <-ti.C:
b := Read(t)
if b == nil {
continue
}
if bytes.Compare(last, b) != 0 {
recv <- b
last = b
}
}
}
}()
return recv
}
-80
View File
@@ -1,80 +0,0 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build ios
package clipboard
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Foundation -framework UIKit -framework MobileCoreServices
#import <stdlib.h>
void clipboard_write_string(char *s);
char *clipboard_read_string();
*/
import "C"
import (
"bytes"
"context"
"time"
"unsafe"
)
func initialize() error { return nil }
func read(t Format) (buf []byte, err error) {
switch t {
case FmtText:
return []byte(C.GoString(C.clipboard_read_string())), nil
case FmtImage:
return nil, errUnsupported
default:
return nil, errUnsupported
}
}
// SetContent sets the clipboard content for iOS
func write(t Format, buf []byte) (<-chan struct{}, error) {
done := make(chan struct{}, 1)
switch t {
case FmtText:
cs := C.CString(string(buf))
defer C.free(unsafe.Pointer(cs))
C.clipboard_write_string(cs)
return done, nil
case FmtImage:
return nil, errUnsupported
default:
return nil, errUnsupported
}
}
func watch(ctx context.Context, t Format) <-chan []byte {
recv := make(chan []byte, 1)
ti := time.NewTicker(time.Second)
last := Read(t)
go func() {
for {
select {
case <-ctx.Done():
close(recv)
return
case <-ti.C:
b := Read(t)
if b == nil {
continue
}
if bytes.Compare(last, b) != 0 {
recv <- b
last = b
}
}
}
}()
return recv
}
-20
View File
@@ -1,20 +0,0 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build ios
#import <UIKit/UIKit.h>
#import <MobileCoreServices/MobileCoreServices.h>
void clipboard_write_string(char *s) {
NSString *value = [NSString stringWithUTF8String:s];
[[UIPasteboard generalPasteboard] setString:value];
}
char *clipboard_read_string() {
NSString *str = [[UIPasteboard generalPasteboard] string];
return (char *)[str UTF8String];
}
-336
View File
@@ -1,336 +0,0 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
package clipboard_test
import (
"bytes"
"context"
"errors"
"image/color"
"image/png"
"os"
"reflect"
"runtime"
"testing"
"time"
"golang.design/x/clipboard"
)
func init() {
clipboard.Debug = true
}
func TestClipboardInit(t *testing.T) {
t.Run("no-cgo", func(t *testing.T) {
if val, ok := os.LookupEnv("CGO_ENABLED"); !ok || val != "0" {
t.Skip("CGO_ENABLED is set to 1")
}
if runtime.GOOS == "windows" {
t.Skip("Windows does not need to check for cgo")
}
if err := clipboard.Init(); !errors.Is(err, clipboard.ErrCgoDisabled) {
t.Fatalf("expect ErrCgoDisabled, got: %v", err)
}
})
t.Run("with-cgo", func(t *testing.T) {
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
t.Skip("CGO_ENABLED is set to 0")
}
if runtime.GOOS != "linux" {
t.Skip("Only Linux may return error at the moment.")
}
if err := clipboard.Init(); err != nil && !errors.Is(err, clipboard.ErrUnavailable) {
t.Fatalf("expect ErrUnavailable, but got: %v", err)
}
})
}
func TestClipboard(t *testing.T) {
if runtime.GOOS != "windows" {
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
t.Skip("CGO_ENABLED is set to 0")
}
}
t.Run("image", func(t *testing.T) {
data, err := os.ReadFile("tests/testdata/clipboard.png")
if err != nil {
t.Fatalf("failed to read gold file: %v", err)
}
clipboard.Write(clipboard.FmtImage, data)
b := clipboard.Read(clipboard.FmtText)
if b != nil {
t.Fatalf("read clipboard that stores image data as text should fail, but got len: %d", len(b))
}
b = clipboard.Read(clipboard.FmtImage)
if b == nil {
t.Fatalf("read clipboard that stores image data as image should success, but got: nil")
}
img1, err := png.Decode(bytes.NewReader(data))
if err != nil {
t.Fatalf("write image is not png encoded: %v", err)
}
img2, err := png.Decode(bytes.NewReader(b))
if err != nil {
t.Fatalf("read image is not png encoded: %v", err)
}
w := img2.Bounds().Dx()
h := img2.Bounds().Dy()
incorrect := 0
for i := 0; i < w; i++ {
for j := 0; j < h; j++ {
wr, wg, wb, wa := img1.At(i, j).RGBA()
gr, gg, gb, ga := img2.At(i, j).RGBA()
want := color.RGBA{
R: uint8(wr),
G: uint8(wg),
B: uint8(wb),
A: uint8(wa),
}
got := color.RGBA{
R: uint8(gr),
G: uint8(gg),
B: uint8(gb),
A: uint8(ga),
}
if !reflect.DeepEqual(want, got) {
t.Logf("read data from clipbaord is inconsistent with previous written data, pix: (%d,%d), got: %+v, want: %+v", i, j, got, want)
incorrect++
}
}
}
if incorrect > 0 {
t.Fatalf("read data from clipboard contains too much inconsistent pixels to the previous written data, number of incorrect pixels: %v", incorrect)
}
})
t.Run("text", func(t *testing.T) {
data := []byte("golang.design/x/clipboard")
clipboard.Write(clipboard.FmtText, data)
b := clipboard.Read(clipboard.FmtImage)
if b != nil {
t.Fatalf("read clipboard that stores text data as image should fail, but got len: %d", len(b))
}
b = clipboard.Read(clipboard.FmtText)
if b == nil {
t.Fatal("read clipboard taht stores text data as text should success, but got: nil")
}
if !reflect.DeepEqual(data, b) {
t.Fatalf("read data from clipbaord is inconsistent with previous written data, got: %d, want: %d", len(b), len(data))
}
})
}
func TestClipboardMultipleWrites(t *testing.T) {
if runtime.GOOS != "windows" {
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
t.Skip("CGO_ENABLED is set to 0")
}
}
data, err := os.ReadFile("tests/testdata/clipboard.png")
if err != nil {
t.Fatalf("failed to read gold file: %v", err)
}
chg := clipboard.Write(clipboard.FmtImage, data)
data = []byte("golang.design/x/clipboard")
clipboard.Write(clipboard.FmtText, data)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
select {
case <-ctx.Done():
t.Fatalf("failed to receive clipboard change notification")
case _, ok := <-chg:
if !ok {
t.Fatalf("change channel is closed before receiving the changed clipboard data")
}
}
_, ok := <-chg
if ok {
t.Fatalf("changed channel should be closed after receiving the notification")
}
b := clipboard.Read(clipboard.FmtImage)
if b != nil {
t.Fatalf("read clipboard that should store text data as image should fail, but got: %d", len(b))
}
b = clipboard.Read(clipboard.FmtText)
if b == nil {
t.Fatalf("read clipboard that should store text data as text should success, got: nil")
}
if !reflect.DeepEqual(data, b) {
t.Fatalf("read data from clipbaord is inconsistent with previous write, want %s, got: %s", string(data), string(b))
}
}
func TestClipboardConcurrentRead(t *testing.T) {
if runtime.GOOS != "windows" {
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
t.Skip("CGO_ENABLED is set to 0")
}
}
// This test check that concurrent read/write to the clipboard does
// not cause crashes on some specific platform, such as macOS.
done := make(chan bool, 2)
go func() {
defer func() {
done <- true
}()
clipboard.Read(clipboard.FmtText)
}()
go func() {
defer func() {
done <- true
}()
clipboard.Read(clipboard.FmtImage)
}()
<-done
<-done
}
func TestClipboardWriteEmpty(t *testing.T) {
if runtime.GOOS != "windows" {
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
t.Skip("CGO_ENABLED is set to 0")
}
}
chg1 := clipboard.Write(clipboard.FmtText, nil)
if got := clipboard.Read(clipboard.FmtText); got != nil {
t.Fatalf("write nil to clipboard should read nil, got: %v", string(got))
}
clipboard.Write(clipboard.FmtText, []byte(""))
<-chg1
if got := clipboard.Read(clipboard.FmtText); string(got) != "" {
t.Fatalf("write empty string to clipboard should read empty string, got: `%v`", string(got))
}
}
func TestClipboardWatch(t *testing.T) {
if runtime.GOOS != "windows" {
if val, ok := os.LookupEnv("CGO_ENABLED"); ok && val == "0" {
t.Skip("CGO_ENABLED is set to 0")
}
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
// clear clipboard
clipboard.Write(clipboard.FmtText, []byte(""))
lastRead := clipboard.Read(clipboard.FmtText)
changed := clipboard.Watch(ctx, clipboard.FmtText)
want := []byte("golang.design/x/clipboard")
go func(ctx context.Context) {
t := time.NewTicker(time.Millisecond * 500)
for {
select {
case <-ctx.Done():
return
case <-t.C:
clipboard.Write(clipboard.FmtText, want)
}
}
}(ctx)
for {
select {
case <-ctx.Done():
if string(lastRead) == "" {
t.Fatalf("clipboard watch never receives a notification")
}
t.Log(string(lastRead))
return
case data, ok := <-changed:
if !ok {
if string(lastRead) == "" {
t.Fatalf("clipboard watch never receives a notification")
}
return
}
if !bytes.Equal(data, want) {
t.Fatalf("received data from watch mismatch, want: %v, got %v", string(want), string(data))
}
lastRead = data
}
}
}
func BenchmarkClipboard(b *testing.B) {
b.Run("text", func(b *testing.B) {
data := []byte("golang.design/x/clipboard")
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
clipboard.Write(clipboard.FmtText, data)
_ = clipboard.Read(clipboard.FmtText)
}
})
}
func TestClipboardNoCgo(t *testing.T) {
if val, ok := os.LookupEnv("CGO_ENABLED"); !ok || val != "0" {
t.Skip("CGO_ENABLED is set to 1")
}
if runtime.GOOS == "windows" {
t.Skip("Windows should always be tested")
}
t.Run("Read", func(t *testing.T) {
defer func() {
if r := recover(); r != nil {
return
}
t.Fatalf("expect to fail when CGO_ENABLED=0")
}()
clipboard.Read(clipboard.FmtText)
})
t.Run("Write", func(t *testing.T) {
defer func() {
if r := recover(); r != nil {
return
}
t.Fatalf("expect to fail when CGO_ENABLED=0")
}()
clipboard.Write(clipboard.FmtText, []byte("dummy"))
})
t.Run("Watch", func(t *testing.T) {
defer func() {
if r := recover(); r != nil {
return
}
t.Fatalf("expect to fail when CGO_ENABLED=0")
}()
clipboard.Watch(context.TODO(), clipboard.FmtText)
})
}
@@ -1,33 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2021 The golang.design Initiative Authors.
All rights reserved. Use of this source code is governed
by a MIT license that can be found in the LICENSE file.
Written by Changkun Ou <changkun.de>
-->
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="design.golang.clipboard.gclip"
android:versionCode="1"
android:versionName="1.0">
<!-- In order to access the clipboard, the application manifest must
specify the permission requirement. See the following page for
details.
http://developer.android.com/guide/topics/manifest/manifest-intro.html#perms -->
<uses-permission android:name="android.permission.CLIPBOARD" />
<application android:label="gclip" android:debuggable="true">
<activity android:name="org.golang.app.GoNativeActivity"
android:label="Gclip"
android:configChanges="orientation|keyboardHidden">
<meta-data android:name="android.app.lib_name" android:value="Gclip" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -1,31 +0,0 @@
# gclip-gui
This is a very basic example for verification purpose that demonstrates
how the [golang.design/x/clipboard](https://golang.design/x/clipboard)
can interact with macOS/Linux/Windows/Android/iOS system clipboard.
The gclip GUI application writes a string to the system clipboard
periodically then reads it back and renders it if possible.
Because of the system limitation, on mobile devices, only string data is
supported at the moment. Hence, one must use clipboard.FmtText. Other supplied
formats result in a panic.
This example is intentded as cross platform application. To build it, one
must use [gomobile](https://golang.org/x/mobile). You may follow the instructions
provided in the [GoMobile wiki](https://github.com/golang/go/wiki/Mobile) page.
- For desktop: `go build -o gclip-gui`
- For Android: `gomobile build -v -target=android -o gclip-gui.apk`
- For iOS: `gomobile build -v -target=ios -bundleid design.golang.gclip-gui.app`
## Screenshots
| macOS | iOS | Windows | Android | Linux |
|:-----:|:---:|:-------:|:-------:|:-----:|
|![](../../tests/testdata/darwin.png)|![](../../tests/testdata/ios.png)|![](../../tests/testdata/windows.png)|![](../../tests/testdata/android.png)|![](../../tests/testdata/linux.png)|
## License
MIT | &copy; 2021 The golang.design Initiative Authors, written by [Changkun Ou](https://changkun.de).
@@ -1,236 +0,0 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build android || ios || linux || darwin || windows
// This is a very basic example for verification purpose that
// demonstrates how the golang.design/x/clipboard can interact
// with macOS/Linux/Windows/Android/iOS system clipboard.
//
// The gclip GUI application writes a string to the system clipboard
// periodically then reads it back and renders it if possible.
//
// Because of the system limitation, on mobile devices, only string
// data is supported at the moment. Hence, one must use clipboard.FmtText.
// Other supplied formats result in a panic.
//
// This example is intentded as cross platform application.
// To build it, one must use gomobile (https://golang.org/x/mobile).
// You may follow the instructions provided in the GoMobile's wiki page:
// https://github.com/golang/go/wiki/Mobile.
//
// - For desktop:
//
// go build -o gclip-gui
//
// - For Android:
//
// gomobile build -v -target=android -o gclip-gui.apk
//
// - For iOS:
//
// gomobile build -v -target=ios -bundleid design.golang.gclip-gui.app
//
package main
import (
"fmt"
"image"
"image/color"
"log"
"os"
"sync"
"time"
"golang.design/x/clipboard"
"golang.org/x/image/font"
"golang.org/x/image/font/basicfont"
"golang.org/x/image/math/fixed"
"golang.org/x/mobile/app"
"golang.org/x/mobile/event/lifecycle"
"golang.org/x/mobile/event/paint"
"golang.org/x/mobile/event/size"
"golang.org/x/mobile/exp/gl/glutil"
"golang.org/x/mobile/geom"
"golang.org/x/mobile/gl"
)
type Label struct {
sz size.Event
images *glutil.Images
m *glutil.Image
drawer *font.Drawer
mu sync.Mutex
data string
}
func NewLabel(images *glutil.Images) *Label {
return &Label{
images: images,
data: "Hello! Gclip.",
drawer: nil,
}
}
func (l *Label) SetLabel(s string) {
l.mu.Lock()
defer l.mu.Unlock()
l.data = s
}
const (
lineWidth = 100
lineHeight = 120
)
func (l *Label) Draw(sz size.Event) {
l.mu.Lock()
s := l.data
l.mu.Unlock()
imgW, imgH := lineWidth*basicfont.Face7x13.Width, lineHeight*basicfont.Face7x13.Height
if sz.WidthPx == 0 && sz.HeightPx == 0 {
return
}
if imgW > sz.WidthPx {
imgW = sz.WidthPx
}
if l.sz != sz {
l.sz = sz
if l.m != nil {
l.m.Release()
}
l.m = l.images.NewImage(imgW, imgH)
}
// Clear the drawing image.
for i := 0; i < len(l.m.RGBA.Pix); i++ {
l.m.RGBA.Pix[i] = 0
}
l.drawer = &font.Drawer{
Dst: l.m.RGBA,
Src: image.NewUniform(color.RGBA{0, 100, 125, 255}),
Face: basicfont.Face7x13,
Dot: fixed.P(5, 10),
}
l.drawer.DrawString(s)
l.m.Upload()
l.m.Draw(
sz,
geom.Point{X: 0, Y: 50},
geom.Point{X: geom.Pt(imgW), Y: 50},
geom.Point{X: 0, Y: geom.Pt(imgH)},
l.m.RGBA.Bounds(),
)
}
func (l *Label) Release() {
if l.m != nil {
l.m.Release()
l.m = nil
l.images = nil
}
}
// GclipApp is the application instance.
type GclipApp struct {
app app.App
ctx gl.Context
siz size.Event
images *glutil.Images
l *Label
counter int
}
// WatchClipboard watches the system clipboard every seconds.
func (g *GclipApp) WatchClipboard() {
go func() {
tk := time.NewTicker(time.Second)
for range tk.C {
// Write something to the clipboard
w := fmt.Sprintf("(gclip: %d)", g.counter)
clipboard.Write(clipboard.FmtText, []byte(w))
g.counter++
log.Println(w)
// Read it back and render it, if possible.
data := clipboard.Read(clipboard.FmtText)
if len(data) == 0 {
continue
}
// Set the current clipboard data as label content and render on the screen.
r := fmt.Sprintf("clipboard: %s", string(data))
g.l.SetLabel(r)
g.app.Send(paint.Event{})
}
}()
}
func (g *GclipApp) OnStart(e lifecycle.Event) {
g.ctx, _ = e.DrawContext.(gl.Context)
g.images = glutil.NewImages(g.ctx)
g.l = NewLabel(g.images)
g.app.Send(paint.Event{})
}
func (g *GclipApp) OnStop() {
g.l.Release()
g.images.Release()
g.ctx = nil
}
func (g *GclipApp) OnSize(size size.Event) {
g.siz = size
}
func (g *GclipApp) OnDraw() {
if g.ctx == nil {
return
}
defer g.app.Send(paint.Event{})
defer g.app.Publish()
g.ctx.ClearColor(0, 0, 0, 1)
g.ctx.Clear(gl.COLOR_BUFFER_BIT)
g.l.Draw(g.siz)
}
func init() {
err := clipboard.Init()
if err != nil {
panic(err)
}
}
func main() {
app.Main(func(a app.App) {
gclip := GclipApp{app: a}
gclip.app.Send(size.Event{WidthPx: 800, HeightPx: 500})
gclip.WatchClipboard()
for e := range gclip.app.Events() {
switch e := gclip.app.Filter(e).(type) {
case lifecycle.Event:
switch e.Crosses(lifecycle.StageVisible) {
case lifecycle.CrossOn:
gclip.OnStart(e)
case lifecycle.CrossOff:
gclip.OnStop()
os.Exit(0)
}
case size.Event:
gclip.OnSize(e)
case paint.Event:
gclip.OnDraw()
}
}
})
}
@@ -1,40 +0,0 @@
# gclip
`gclip` command offers the ability to interact with the system clipboard
from the shell. To install:
```bash
$ go install golang.design/x/clipboard/cmd/gclip@latest
```
```bash
$ gclip
gclip is a command that provides clipboard interaction.
usage: gclip [-copy|-paste] [-f <file>]
options:
-copy
copy data to clipboard
-f string
source or destination to a given file path
-paste
paste data from clipboard
examples:
gclip -paste paste from clipboard and prints the content
gclip -paste -f x.txt paste from clipboard and save as text to x.txt
gclip -paste -f x.png paste from clipboard and save as image to x.png
cat x.txt | gclip -copy copy content from x.txt to clipboard
gclip -copy -f x.txt copy content from x.txt to clipboard
gclip -copy -f x.png copy x.png as image data to clipboard
```
If `-copy` is used, the command will exit when the data is no longer
available from the clipboard. You can always send the command to the
background using a shell `&` operator, for example:
```bash
$ cat x.txt | gclip -copy &
```
## License
MIT | &copy; 2021 The golang.design Initiative Authors, written by [Changkun Ou](https://changkun.de).
-131
View File
@@ -1,131 +0,0 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
package main // go install golang.design/x/clipboard/cmd/gclip@latest
import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"golang.design/x/clipboard"
)
func usage() {
fmt.Fprintf(os.Stderr, `gclip is a command that provides clipboard interaction.
usage: gclip [-copy|-paste] [-f <file>]
options:
`)
flag.PrintDefaults()
fmt.Fprintf(os.Stderr, `
examples:
gclip -paste paste from clipboard and prints the content
gclip -paste -f x.txt paste from clipboard and save as text to x.txt
gclip -paste -f x.png paste from clipboard and save as image to x.png
cat x.txt | gclip -copy copy content from x.txt to clipboard
gclip -copy -f x.txt copy content from x.txt to clipboard
gclip -copy -f x.png copy x.png as image data to clipboard
`)
os.Exit(2)
}
var (
in = flag.Bool("copy", false, "copy data to clipboard")
out = flag.Bool("paste", false, "paste data from clipboard")
file = flag.String("f", "", "source or destination to a given file path")
)
func init() {
err := clipboard.Init()
if err != nil {
panic(err)
}
}
func main() {
flag.Usage = usage
flag.Parse()
if *out {
if err := pst(); err != nil {
usage()
}
return
}
if *in {
if err := cpy(); err != nil {
usage()
}
return
}
usage()
}
func cpy() error {
t := clipboard.FmtText
ext := filepath.Ext(*file)
switch ext {
case ".png":
t = clipboard.FmtImage
case ".txt":
fallthrough
default:
t = clipboard.FmtText
}
var (
b []byte
err error
)
if *file != "" {
b, err = os.ReadFile(*file)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to read given file: %v", err)
return err
}
} else {
b, err = io.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to read from stdin: %v", err)
return err
}
}
// Wait until clipboard content has been changed.
<-clipboard.Write(t, b)
return nil
}
func pst() (err error) {
var b []byte
b = clipboard.Read(clipboard.FmtText)
if b == nil {
b = clipboard.Read(clipboard.FmtImage)
}
if *file != "" && b != nil {
err = os.WriteFile(*file, b, os.ModePerm)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to write data to file %s: %v", *file, err)
}
return err
}
for len(b) > 0 {
n, err := os.Stdout.Write(b)
if err != nil {
return err
}
b = b[n:]
}
return nil
}
-56
View File
@@ -1,56 +0,0 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
//go:build cgo
package clipboard_test
import (
"context"
"fmt"
"time"
"golang.design/x/clipboard"
)
func ExampleWrite() {
err := clipboard.Init()
if err != nil {
panic(err)
}
clipboard.Write(clipboard.FmtText, []byte("Hello, 世界"))
// Output:
}
func ExampleRead() {
err := clipboard.Init()
if err != nil {
panic(err)
}
fmt.Println(string(clipboard.Read(clipboard.FmtText)))
// Output:
// Hello, 世界
}
func ExampleWatch() {
err := clipboard.Init()
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
changed := clipboard.Watch(context.Background(), clipboard.FmtText)
go func(ctx context.Context) {
clipboard.Write(clipboard.FmtText, []byte("你好,world"))
}(ctx)
fmt.Println(string(<-changed))
// Output:
// 你好,world
}
-14
View File
@@ -1,14 +0,0 @@
// Copyright 2021 The golang.design Initiative Authors.
// All rights reserved. Use of this source code is governed
// by a MIT license that can be found in the LICENSE file.
//
// Written by Changkun Ou <changkun.de>
package clipboard
// for debugging errors
var (
Debug = debug
ErrUnavailable = errUnavailable
ErrCgoDisabled = errNoCgo
)
-13
View File
@@ -1,13 +0,0 @@
module golang.design/x/clipboard
go 1.24
require (
golang.org/x/image v0.28.0
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f
)
require (
golang.org/x/exp/shiny v0.0.0-20250606033433-dcc06ee1d476 // indirect
golang.org/x/sys v0.33.0 // indirect
)
-8
View File
@@ -1,8 +0,0 @@
golang.org/x/exp/shiny v0.0.0-20250606033433-dcc06ee1d476 h1:Wdx0vgH5Wgsw+lF//LJKmWOJBLWX6nprsMqnf99rYDE=
golang.org/x/exp/shiny v0.0.0-20250606033433-dcc06ee1d476/go.mod h1:ygj7T6vSGhhm/9yTpOQQNvuAUFziTH7RUiH74EoE2C8=
golang.org/x/image v0.28.0 h1:gdem5JW1OLS4FbkWgLO+7ZeFzYtL3xClb97GaUzYMFE=
golang.org/x/image v0.28.0/go.mod h1:GUJYXtnGKEUgggyzh+Vxt+AviiCcyiwpsl8iQ8MvwGY=
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f h1:/n+PL2HlfqeSiDCuhdBbRNlGS/g2fM4OHufalHaTVG8=
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f/go.mod h1:ESkJ836Z6LpG6mTVAhA48LpfW/8fNR0ifStlH2axyfg=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
-109
View File
@@ -1,109 +0,0 @@
#!/bin/bash
# Test script for Linux CGO-free clipboard implementation
echo "Testing Linux clipboard implementation without CGO..."
# Check for required tools
echo "Checking for clipboard tools..."
for tool in xclip xsel wl-copy; do
if command -v $tool &> /dev/null; then
echo "$tool is installed"
else
echo "$tool is not installed"
fi
done
# Create test program
cat > test_linux_clipboard.go << 'EOF'
package main
import (
"fmt"
"log"
"os"
"golang.design/x/clipboard"
)
func main() {
err := clipboard.Init()
if err != nil {
log.Fatal("Failed to initialize clipboard:", err)
}
// Test text
fmt.Println("\n=== Testing Text Clipboard ===")
testText := []byte("Hello from CGO-free Linux clipboard!")
clipboard.Write(clipboard.FmtText, testText)
fmt.Println("Wrote text:", string(testText))
readText := clipboard.Read(clipboard.FmtText)
fmt.Println("Read text:", string(readText))
if string(testText) == string(readText) {
fmt.Println("✓ Text clipboard test passed")
} else {
fmt.Println("✗ Text clipboard test failed")
}
// Test empty write
fmt.Println("\n=== Testing Empty Write ===")
clipboard.Write(clipboard.FmtText, []byte{})
emptyRead := clipboard.Read(clipboard.FmtText)
if emptyRead == nil || len(emptyRead) == 0 {
fmt.Println("✓ Empty write test passed")
} else {
fmt.Println("✗ Empty write test failed, got:", string(emptyRead))
}
// Test image if requested
if len(os.Args) > 1 && os.Args[1] == "image" {
fmt.Println("\n=== Testing Image Clipboard ===")
// Try to read test image
imageData, err := os.ReadFile("tests/testdata/clipboard.png")
if err != nil {
fmt.Println("Could not read test image:", err)
return
}
clipboard.Write(clipboard.FmtImage, imageData)
fmt.Println("Wrote image data, length:", len(imageData))
readImage := clipboard.Read(clipboard.FmtImage)
if readImage != nil {
fmt.Println("Read image data, length:", len(readImage))
if len(imageData) == len(readImage) {
fmt.Println("✓ Image clipboard test passed")
} else {
fmt.Println("✗ Image lengths don't match")
}
} else {
fmt.Println("✗ Failed to read image from clipboard")
}
// Test that reading text from image clipboard returns nil
textFromImage := clipboard.Read(clipboard.FmtText)
if textFromImage == nil {
fmt.Println("✓ Reading text from image clipboard correctly returned nil")
} else {
fmt.Println("✗ Reading text from image clipboard should return nil, got:", string(textFromImage))
}
}
}
EOF
# Run tests with CGO disabled
echo -e "\n=== Running with CGO_ENABLED=0 ==="
CGO_ENABLED=0 go run test_linux_clipboard.go
echo -e "\n=== Running with CGO_ENABLED=0 and image test ==="
CGO_ENABLED=0 go run test_linux_clipboard.go image
# Run actual tests
echo -e "\n=== Running go test with CGO_ENABLED=0 ==="
CGO_ENABLED=0 go test -v -run TestClipboard
# Clean up
rm -f test_linux_clipboard.go
echo -e "\nTest script completed!"
-15
View File
@@ -1,15 +0,0 @@
# Copyright 2021 The golang.design Initiative Authors.
# All rights reserved. Use of this source code is governed
# by a MIT license that can be found in the LICENSE file.
#
# Written by Changkun Ou <changkun.de>
all: test
test:
go test -v -count=1 -covermode=atomic ..
test-docker:
docker build -t golang-design/x/clipboard ..
docker run --rm --name cb golang-design/x/clipboard
docker rmi golang-design/x/clipboard
@@ -1,11 +0,0 @@
# Copyright 2021 The golang.design Initiative Authors.
# All rights reserved. Use of this source code is governed
# by a MIT license that can be found in the LICENSE file.
#
# Written by Changkun Ou <changkun.de>
# require apt-get install xvfb
Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
export DISPLAY=:99.0
go test -v -covermode=atomic ./...
Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

+7 -25
View File
@@ -5,7 +5,6 @@ import (
"encoding/json"
"log/slog"
"os"
"path/filepath"
"strings"
tea "github.com/charmbracelet/bubbletea/v2"
@@ -13,8 +12,9 @@ import (
"github.com/sst/opencode-sdk-go"
"github.com/sst/opencode-sdk-go/option"
"github.com/sst/opencode/internal/app"
"github.com/sst/opencode/internal/clipboard"
"github.com/sst/opencode/internal/tui"
"golang.design/x/clipboard"
"github.com/sst/opencode/internal/util"
)
var Version = "dev"
@@ -39,33 +39,15 @@ func main() {
os.Exit(1)
}
logfile := filepath.Join(appInfo.Path.Data, "log", "tui.log")
if _, err := os.Stat(filepath.Dir(logfile)); os.IsNotExist(err) {
err := os.MkdirAll(filepath.Dir(logfile), 0755)
if err != nil {
slog.Error("Failed to create log directory", "error", err)
os.Exit(1)
}
}
file, err := os.Create(logfile)
if err != nil {
slog.Error("Failed to create log file", "error", err)
os.Exit(1)
}
defer file.Close()
logger := slog.New(slog.NewTextHandler(file, &slog.HandlerOptions{Level: slog.LevelDebug}))
slog.SetDefault(logger)
slog.Debug("TUI launched", "app", appInfo)
httpClient := opencode.NewClient(
option.WithBaseURL(url),
)
if err != nil {
slog.Error("Failed to create client", "error", err)
os.Exit(1)
}
apiHandler := util.NewAPILogHandler(httpClient, "tui", slog.LevelDebug)
logger := slog.New(apiHandler)
slog.SetDefault(logger)
slog.Debug("TUI launched", "app", appInfo)
go func() {
err = clipboard.Init()
+2 -8
View File
@@ -17,14 +17,11 @@ require (
github.com/muesli/termenv v0.16.0
github.com/sergi/go-diff v1.3.2-0.20230802210424-5b0b94c5c0d3
github.com/sst/opencode-sdk-go v0.1.0-alpha.8
golang.design/x/clipboard v0.7.1
golang.org/x/image v0.28.0
rsc.io/qr v0.2.0
)
replace (
github.com/sst/opencode-sdk-go => ./sdk
golang.design/x/clipboard => ./clipboard
)
replace github.com/sst/opencode-sdk-go => ./sdk
require golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect
@@ -58,8 +55,6 @@ require (
github.com/tidwall/pretty v1.2.1 // indirect
github.com/tidwall/sjson v1.2.5 // indirect
github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect
golang.org/x/exp/shiny v0.0.0-20250620022241-b7579e27df2b // indirect
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f // indirect
golang.org/x/mod v0.25.0 // indirect
golang.org/x/tools v0.34.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
@@ -87,7 +82,6 @@ require (
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
github.com/yuin/goldmark v1.7.8 // indirect
github.com/yuin/goldmark-emoji v1.0.5 // indirect
golang.org/x/image v0.28.0 // indirect
golang.org/x/net v0.41.0 // indirect
golang.org/x/sync v0.15.0 // indirect
golang.org/x/sys v0.33.0 // indirect
-4
View File
@@ -216,12 +216,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
golang.org/x/exp/shiny v0.0.0-20250620022241-b7579e27df2b h1:zELBzk+7ERc6m8BxhzU2VYjp03wlEvi+cIgYQR5H3CI=
golang.org/x/exp/shiny v0.0.0-20250620022241-b7579e27df2b/go.mod h1:ygj7T6vSGhhm/9yTpOQQNvuAUFziTH7RUiH74EoE2C8=
golang.org/x/image v0.28.0 h1:gdem5JW1OLS4FbkWgLO+7ZeFzYtL3xClb97GaUzYMFE=
golang.org/x/image v0.28.0/go.mod h1:GUJYXtnGKEUgggyzh+Vxt+AviiCcyiwpsl8iQ8MvwGY=
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f h1:/n+PL2HlfqeSiDCuhdBbRNlGS/g2fM4OHufalHaTVG8=
golang.org/x/mobile v0.0.0-20250606033058-a2a15c67f36f/go.mod h1:ESkJ836Z6LpG6mTVAhA48LpfW/8fNR0ifStlH2axyfg=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
+1 -1
View File
@@ -12,13 +12,13 @@ import (
tea "github.com/charmbracelet/bubbletea/v2"
"github.com/sst/opencode-sdk-go"
"github.com/sst/opencode/internal/clipboard"
"github.com/sst/opencode/internal/commands"
"github.com/sst/opencode/internal/components/toast"
"github.com/sst/opencode/internal/config"
"github.com/sst/opencode/internal/styles"
"github.com/sst/opencode/internal/theme"
"github.com/sst/opencode/internal/util"
"golang.design/x/clipboard"
)
type App struct {
@@ -53,7 +53,7 @@ clipboard data is changed, use the watcher API:
println(string(data))
}
*/
package clipboard // import "golang.design/x/clipboard"
package clipboard
import (
"context"
@@ -4,7 +4,7 @@
//
// Written by Changkun Ou <changkun.de>
//go:build darwin && !ios
//go:build darwin
package clipboard
@@ -4,7 +4,7 @@
//
// Written by Changkun Ou <changkun.de>
//go:build linux && !android
//go:build linux
package clipboard
@@ -12,6 +12,7 @@ import (
"bytes"
"context"
"fmt"
"log/slog"
"os/exec"
"strings"
"sync"
@@ -72,11 +73,13 @@ func initialize() error {
clipboardTools[i].available = true
if selectedTool < 0 {
selectedTool = i
slog.Debug("Clipboard tool found", "tool", tool.name)
}
}
}
if selectedTool < 0 {
slog.Warn("No clipboard utility found on system. Copy/paste functionality will be disabled.")
return fmt.Errorf(`%w: No clipboard utility found. Install one of the following:
For X11 systems:
@@ -98,6 +101,12 @@ If running in a headless environment, you may also need:
}
func read(t Format) (buf []byte, err error) {
// Ensure clipboard is initialized before attempting to read
if err := initialize(); err != nil {
slog.Debug("Clipboard read failed: not initialized", "error", err)
return nil, err
}
toolMutex.Lock()
tool := clipboardTools[selectedTool]
toolMutex.Unlock()
@@ -167,6 +176,11 @@ func readImage(tool struct {
}
func write(t Format, buf []byte) (<-chan struct{}, error) {
// Ensure clipboard is initialized before attempting to write
if err := initialize(); err != nil {
return nil, err
}
toolMutex.Lock()
tool := clipboardTools[selectedTool]
toolMutex.Unlock()
@@ -230,6 +244,13 @@ func write(t Format, buf []byte) (<-chan struct{}, error) {
func watch(ctx context.Context, t Format) <-chan []byte {
recv := make(chan []byte, 1)
// Ensure clipboard is initialized before starting watch
if err := initialize(); err != nil {
close(recv)
return recv
}
ti := time.NewTicker(time.Second)
// Get initial clipboard content
@@ -42,7 +42,7 @@ func (cg *filesAndFoldersContextGroup) getGitFiles() []dialog.CompletionItemI {
})
for _, file := range files {
title := file.File
title := file.Path
if file.Added > 0 {
title += green(" +" + strconv.Itoa(int(file.Added)))
}
@@ -51,7 +51,7 @@ func (cg *filesAndFoldersContextGroup) getGitFiles() []dialog.CompletionItemI {
}
item := dialog.NewCompletionItem(dialog.CompletionItem{
Title: title,
Value: file.File,
Value: file.Path,
})
items = append(items, item)
}
@@ -15,13 +15,13 @@ import (
"github.com/google/uuid"
"github.com/sst/opencode-sdk-go"
"github.com/sst/opencode/internal/app"
"github.com/sst/opencode/internal/clipboard"
"github.com/sst/opencode/internal/commands"
"github.com/sst/opencode/internal/components/dialog"
"github.com/sst/opencode/internal/components/textarea"
"github.com/sst/opencode/internal/styles"
"github.com/sst/opencode/internal/theme"
"github.com/sst/opencode/internal/util"
"golang.design/x/clipboard"
)
type EditorComponent interface {
@@ -30,6 +30,7 @@ type EditorComponent interface {
Content(width int) string
Lines() int
Value() string
Length() int
Focused() bool
Focus() (tea.Model, tea.Cmd)
Blur()
@@ -38,6 +39,7 @@ type EditorComponent interface {
Paste() (tea.Model, tea.Cmd)
Newline() (tea.Model, tea.Cmd)
SetInterruptKeyInDebounce(inDebounce bool)
SetExitKeyInDebounce(inDebounce bool)
}
type editorComponent struct {
@@ -45,6 +47,7 @@ type editorComponent struct {
textarea textarea.Model
spinner spinner.Model
interruptKeyInDebounce bool
exitKeyInDebounce bool
}
func (m *editorComponent) Init() tea.Cmd {
@@ -93,7 +96,16 @@ func (m *editorComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case ".pdf":
mediaType = "application/pdf"
default:
mediaType = "text/plain"
attachment := &textarea.Attachment{
ID: uuid.NewString(),
Display: "@" + filePath,
URL: fmt.Sprintf("file://./%s", filePath),
Filename: filePath,
MediaType: "text/plain",
}
m.textarea.InsertAttachment(attachment)
m.textarea.InsertString(" ")
return m, nil
}
fileBytes, err := os.ReadFile(filePath)
@@ -224,7 +236,10 @@ func (m *editorComponent) Content(width int) string {
Render(textarea)
hint := base(m.getSubmitKeyText()) + muted(" send ")
if m.app.IsBusy() {
if m.exitKeyInDebounce {
keyText := m.getExitKeyText()
hint = base(keyText+" again") + muted(" to exit")
} else if m.app.IsBusy() {
keyText := m.getInterruptKeyText()
if m.interruptKeyInDebounce {
hint = muted(
@@ -290,6 +305,10 @@ func (m *editorComponent) Value() string {
return m.textarea.Value()
}
func (m *editorComponent) Length() int {
return m.textarea.Length()
}
func (m *editorComponent) Submit() (tea.Model, tea.Cmd) {
value := strings.TrimSpace(m.Value())
if value == "" {
@@ -365,6 +384,10 @@ func (m *editorComponent) SetInterruptKeyInDebounce(inDebounce bool) {
m.interruptKeyInDebounce = inDebounce
}
func (m *editorComponent) SetExitKeyInDebounce(inDebounce bool) {
m.exitKeyInDebounce = inDebounce
}
func (m *editorComponent) getInterruptKeyText() string {
return m.app.Commands[commands.SessionInterruptCommand].Keys()[0]
}
@@ -373,6 +396,10 @@ func (m *editorComponent) getSubmitKeyText() string {
return m.app.Commands[commands.InputSubmitCommand].Keys()[0]
}
func (m *editorComponent) getExitKeyText() string {
return m.app.Commands[commands.AppExitCommand].Keys()[0]
}
func (m *editorComponent) resetTextareaStyles() textarea.Model {
t := theme.CurrentTheme()
bgColor := t.BackgroundElement()
@@ -134,7 +134,6 @@ func renderContentBlock(
style := styles.NewStyle().
Foreground(renderer.textColor).
Background(t.BackgroundPanel()).
Width(width).
PaddingTop(renderer.paddingTop).
PaddingBottom(renderer.paddingBottom).
PaddingLeft(renderer.paddingLeft).
@@ -232,16 +231,15 @@ func renderText(
if highlight {
backgroundColor = t.BackgroundElement()
}
messageStyle := styles.NewStyle().Background(backgroundColor)
content := messageStyle.Render(text)
var content string
switch casted := message.(type) {
case opencode.AssistantMessage:
ts = time.UnixMilli(int64(casted.Time.Created))
content = util.ToMarkdown(text, width, backgroundColor)
case opencode.UserMessage:
ts = time.UnixMilli(int64(casted.Time.Created))
messageStyle = messageStyle.Width(width - 6)
messageStyle := styles.NewStyle().Background(backgroundColor).Width(width - 6)
content = messageStyle.Render(text)
}
timestamp := ts.
@@ -307,8 +305,10 @@ func renderToolDetails(
return ""
}
if toolCall.State.Status == opencode.ToolPartStateStatusPending || toolCall.State.Status == opencode.ToolPartStateStatusRunning {
if toolCall.State.Status == opencode.ToolPartStateStatusPending ||
toolCall.State.Status == opencode.ToolPartStateStatusRunning {
title := renderToolTitle(toolCall, width)
title = styles.NewStyle().Width(width - 6).Render(title)
return renderContentBlock(app, title, highlight, width)
}
@@ -457,6 +457,7 @@ func renderToolDetails(
}
body = *result
body = util.TruncateHeight(body, 10)
body = styles.NewStyle().Width(width - 6).Render(body)
}
}
@@ -467,6 +468,7 @@ func renderToolDetails(
if error != "" {
body = styles.NewStyle().
Width(width - 6).
Foreground(t.Error()).
Background(backgroundColor).
Render(error)
@@ -475,6 +477,7 @@ func renderToolDetails(
if body == "" && error == "" && result != nil {
body = *result
body = util.TruncateHeight(body, 10)
body = styles.NewStyle().Width(width - 6).Render(body)
}
title := renderToolTitle(toolCall, width)
@@ -328,6 +328,7 @@ func (m *messagesComponent) renderView(width int) {
}
if error != "" {
error = styles.NewStyle().Width(width - 6).Render(error)
error = renderContentBlock(
m.app,
error,
@@ -2,6 +2,7 @@ package dialog
import (
"log/slog"
"strings"
"github.com/charmbracelet/bubbles/v2/key"
"github.com/charmbracelet/bubbles/v2/textarea"
@@ -87,6 +88,7 @@ type completionDialogComponent struct {
height int
pseudoSearchTextArea textarea.Model
list list.List[CompletionItemI]
trigger string
}
type completionDialogKeyMap struct {
@@ -119,8 +121,8 @@ func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
c.pseudoSearchTextArea, cmd = c.pseudoSearchTextArea.Update(msg)
cmds = append(cmds, cmd)
var query string
query = c.pseudoSearchTextArea.Value()
fullValue := c.pseudoSearchTextArea.Value()
query := strings.TrimPrefix(fullValue, c.trigger)
if query != c.query {
c.query = query
@@ -147,8 +149,9 @@ func (c *completionDialogComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
return c, c.complete(item)
case key.Matches(msg, completionDialogKeys.Cancel):
// Only close on backspace when there are no characters left
if msg.String() != "backspace" || len(c.pseudoSearchTextArea.Value()) <= 0 {
// Only close on backspace when there are no characters left, unless we're back to just the trigger
value := c.pseudoSearchTextArea.Value()
if msg.String() != "backspace" || (len(value) <= len(c.trigger) && value != c.trigger) {
return c, c.close()
}
}
@@ -227,7 +230,7 @@ func (c *completionDialogComponent) close() tea.Cmd {
return util.CmdHandler(CompletionDialogCloseMsg{})
}
func NewCompletionDialogComponent(completionProvider CompletionProvider) CompletionDialog {
func NewCompletionDialogComponent(completionProvider CompletionProvider, trigger string) CompletionDialog {
ti := textarea.New()
li := list.NewListComponent(
@@ -245,10 +248,14 @@ func NewCompletionDialogComponent(completionProvider CompletionProvider) Complet
li.SetItems(items)
}()
// Initialize the textarea with the trigger character
ti.SetValue(trigger)
return &completionDialogComponent{
query: "",
completionProvider: completionProvider,
pseudoSearchTextArea: ti,
list: li,
trigger: trigger,
}
}
+49 -7
View File
@@ -32,15 +32,27 @@ import (
// InterruptDebounceTimeoutMsg is sent when the interrupt key debounce timeout expires
type InterruptDebounceTimeoutMsg struct{}
// ExitDebounceTimeoutMsg is sent when the exit key debounce timeout expires
type ExitDebounceTimeoutMsg struct{}
// InterruptKeyState tracks the state of interrupt key presses for debouncing
type InterruptKeyState int
// ExitKeyState tracks the state of exit key presses for debouncing
type ExitKeyState int
const (
InterruptKeyIdle InterruptKeyState = iota
InterruptKeyFirstPress
)
const (
ExitKeyIdle ExitKeyState = iota
ExitKeyFirstPress
)
const interruptDebounceTimeout = 1 * time.Second
const exitDebounceTimeout = 1 * time.Second
const fileViewerFullWidthCutoff = 160
type appModel struct {
@@ -59,6 +71,7 @@ type appModel struct {
isLeaderSequence bool
toastManager *toast.ToastManager
interruptKeyState InterruptKeyState
exitKeyState ExitKeyState
lastScroll time.Time
messagesRight bool
fileViewer fileviewer.Model
@@ -189,7 +202,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
cmds = append(cmds, cmd)
// Set command provider for command completion
a.completions = dialog.NewCompletionDialogComponent(a.commandProvider)
a.completions = dialog.NewCompletionDialogComponent(a.commandProvider, "/")
updated, cmd = a.completions.Update(msg)
a.completions = updated.(dialog.CompletionDialog)
cmds = append(cmds, cmd)
@@ -208,7 +221,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
cmds = append(cmds, cmd)
// Set file provider for file completion
a.completions = dialog.NewCompletionDialogComponent(a.fileProvider)
a.completions = dialog.NewCompletionDialogComponent(a.fileProvider, "@")
updated, cmd = a.completions.Update(msg)
a.completions = updated.(dialog.CompletionDialog)
cmds = append(cmds, cmd)
@@ -252,7 +265,13 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return a, nil
}
// 6. Handle interrupt key debounce for session interrupt
// 6 Handle input clear command
inputClearCommand := a.app.Commands[commands.InputClearCommand]
if inputClearCommand.Matches(msg, a.isLeaderSequence) && a.editor.Length() > 0 {
return a, util.CmdHandler(commands.ExecuteCommandMsg(inputClearCommand))
}
// 7. Handle interrupt key debounce for session interrupt
interruptCommand := a.app.Commands[commands.SessionInterruptCommand]
if interruptCommand.Matches(msg, a.isLeaderSequence) && a.app.IsBusy() {
switch a.interruptKeyState {
@@ -271,7 +290,26 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
}
// 7. Check again for commands that don't require leader (excluding interrupt when busy)
// 8. Handle exit key debounce for app exit when using non-leader command
exitCommand := a.app.Commands[commands.AppExitCommand]
if exitCommand.Matches(msg, a.isLeaderSequence) {
switch a.exitKeyState {
case ExitKeyIdle:
// First exit key press - start debounce timer
a.exitKeyState = ExitKeyFirstPress
a.editor.SetExitKeyInDebounce(true)
return a, tea.Tick(exitDebounceTimeout, func(t time.Time) tea.Msg {
return ExitDebounceTimeoutMsg{}
})
case ExitKeyFirstPress:
// Second exit key press within timeout - actually exit
a.exitKeyState = ExitKeyIdle
a.editor.SetExitKeyInDebounce(false)
return a, util.CmdHandler(commands.ExecuteCommandMsg(exitCommand))
}
}
// 9. Check again for commands that don't require leader (excluding interrupt when busy and exit when in debounce)
matches := a.app.Commands.Matches(msg, a.isLeaderSequence)
if len(matches) > 0 {
// Skip interrupt key if we're in debounce mode and app is busy
@@ -281,8 +319,7 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return a, util.CmdHandler(commands.ExecuteCommandsMsg(matches))
}
// 7. Fallback to editor. This is for other characters
// like backspace, tab, etc.
// 10. Fallback to editor. This is for other characters like backspace, tab, etc.
updatedEditor, cmd := a.editor.Update(msg)
a.editor = updatedEditor.(chat.EditorComponent)
return a, cmd
@@ -499,6 +536,10 @@ func (a appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
// Reset interrupt key state after timeout
a.interruptKeyState = InterruptKeyIdle
a.editor.SetInterruptKeyInDebounce(false)
case ExitDebounceTimeoutMsg:
// Reset exit key state after timeout
a.exitKeyState = ExitKeyIdle
a.editor.SetExitKeyInDebounce(false)
case dialog.FindSelectedMsg:
return a.openFile(msg.FilePath)
}
@@ -993,7 +1034,7 @@ func NewModel(app *app.App) tea.Model {
messages := chat.NewMessagesComponent(app)
editor := chat.NewEditorComponent(app)
completions := dialog.NewCompletionDialogComponent(commandProvider)
completions := dialog.NewCompletionDialogComponent(commandProvider, "/")
var leaderBinding *key.Binding
if app.Config.Keybinds.Leader != "" {
@@ -1015,6 +1056,7 @@ func NewModel(app *app.App) tea.Model {
fileCompletionActive: false,
toastManager: toast.NewToastManager(),
interruptKeyState: InterruptKeyIdle,
exitKeyState: ExitKeyIdle,
fileViewer: fileviewer.New(app),
messagesRight: app.State.MessagesRight,
}
+123
View File
@@ -0,0 +1,123 @@
package util
import (
"context"
"log/slog"
"sync"
opencode "github.com/sst/opencode-sdk-go"
)
type APILogHandler struct {
client *opencode.Client
service string
level slog.Level
attrs []slog.Attr
groups []string
mu sync.Mutex
}
func NewAPILogHandler(client *opencode.Client, service string, level slog.Level) *APILogHandler {
return &APILogHandler{
client: client,
service: service,
level: level,
attrs: make([]slog.Attr, 0),
groups: make([]string, 0),
}
}
func (h *APILogHandler) Enabled(_ context.Context, level slog.Level) bool {
return level >= h.level
}
func (h *APILogHandler) Handle(ctx context.Context, r slog.Record) error {
var apiLevel opencode.AppLogParamsLevel
switch r.Level {
case slog.LevelDebug:
apiLevel = opencode.AppLogParamsLevelDebug
case slog.LevelInfo:
apiLevel = opencode.AppLogParamsLevelInfo
case slog.LevelWarn:
apiLevel = opencode.AppLogParamsLevelWarn
case slog.LevelError:
apiLevel = opencode.AppLogParamsLevelError
default:
apiLevel = opencode.AppLogParamsLevelInfo
}
extra := make(map[string]any)
h.mu.Lock()
for _, attr := range h.attrs {
extra[attr.Key] = attr.Value.Any()
}
h.mu.Unlock()
r.Attrs(func(attr slog.Attr) bool {
extra[attr.Key] = attr.Value.Any()
return true
})
params := opencode.AppLogParams{
Service: opencode.F(h.service),
Level: opencode.F(apiLevel),
Message: opencode.F(r.Message),
}
if len(extra) > 0 {
params.Extra = opencode.F(extra)
}
go func() {
_, err := h.client.App.Log(context.Background(), params)
if err != nil {
// Fallback: we can't log the error using slog as it would create a loop
// TODO: fallback file?
}
}()
return nil
}
// WithAttrs returns a new Handler whose attributes consist of
// both the receiver's attributes and the arguments.
func (h *APILogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
h.mu.Lock()
defer h.mu.Unlock()
newHandler := &APILogHandler{
client: h.client,
service: h.service,
level: h.level,
attrs: make([]slog.Attr, len(h.attrs)+len(attrs)),
groups: make([]string, len(h.groups)),
}
copy(newHandler.attrs, h.attrs)
copy(newHandler.attrs[len(h.attrs):], attrs)
copy(newHandler.groups, h.groups)
return newHandler
}
// WithGroup returns a new Handler with the given group appended to
// the receiver's existing groups.
func (h *APILogHandler) WithGroup(name string) slog.Handler {
h.mu.Lock()
defer h.mu.Unlock()
newHandler := &APILogHandler{
client: h.client,
service: h.service,
level: h.level,
attrs: make([]slog.Attr, len(h.attrs)),
groups: make([]string, len(h.groups)+1),
}
copy(newHandler.attrs, h.attrs)
copy(newHandler.groups, h.groups)
newHandler.groups[len(h.groups)] = name
return newHandler
}
+4 -4
View File
@@ -1,4 +1,4 @@
configured_endpoints: 20
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-c06a9b8d8284683e8350fdd3eceff0b5756877f7b67e974acd565409b67d32a0.yml
openapi_spec_hash: 5933bca0c79177065374ac724a6bc986
config_hash: de53ecf98e1038f2cc2fd273b582f082
configured_endpoints: 21
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/opencode%2Fopencode-879570c29c56e0a73a0624a84662b7f7c319a3c790c78ec6ac4cf62a7b1a5bd0.yml
openapi_spec_hash: 2432e2dfed22193a0c6b3dfe0f82ec7d
config_hash: 53e3aeb355f3b2e0d10985d6d7635a7e
+8 -6
View File
@@ -19,36 +19,38 @@ Methods:
Response Types:
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#App">App</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#LogLevel">LogLevel</a>
Methods:
- <code title="get /app">client.App.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppService.Get">Get</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#App">App</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /app/init">client.App.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppService.Init">Init</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="post /log">client.App.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppService.Log">Log</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, body <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#AppLogParams">AppLogParams</a>) (<a href="https://pkg.go.dev/builtin#bool">bool</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
# Find
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#FindSymbolsResponse">FindSymbolsResponse</a>
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindTextResponse">FindTextResponse</a>
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Match">Match</a>
- <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Symbol">Symbol</a>
Methods:
- <code title="get /find/file">client.Find.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindService.Files">Files</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindFilesParams">FindFilesParams</a>) ([]<a href="https://pkg.go.dev/builtin#string">string</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /find/symbol">client.Find.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindService.Symbols">Symbols</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindSymbolsParams">FindSymbolsParams</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindSymbolsResponse">FindSymbolsResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /find">client.Find.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindService.Text">Text</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindTextParams">FindTextParams</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindTextResponse">FindTextResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /find/symbol">client.Find.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindService.Symbols">Symbols</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindSymbolsParams">FindSymbolsParams</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Symbol">Symbol</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /find">client.Find.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindService.Text">Text</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FindTextParams">FindTextParams</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#Match">Match</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
# File
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#File">File</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#FileReadResponse">FileReadResponse</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#FileStatusResponse">FileStatusResponse</a>
Methods:
- <code title="get /file">client.File.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FileService.Read">Read</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>, query <a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FileReadParams">FileReadParams</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#FileReadResponse">FileReadResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /file/status">client.File.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FileService.Status">Status</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FileStatusResponse">FileStatusResponse</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
- <code title="get /file/status">client.File.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#FileService.Status">Status</a>(ctx <a href="https://pkg.go.dev/context">context</a>.<a href="https://pkg.go.dev/context#Context">Context</a>) ([]<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go">opencode</a>.<a href="https://pkg.go.dev/github.com/sst/opencode-sdk-go#File">File</a>, <a href="https://pkg.go.dev/builtin#error">error</a>)</code>
# Config
+60
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"github.com/sst/opencode-sdk-go/internal/apijson"
"github.com/sst/opencode-sdk-go/internal/param"
"github.com/sst/opencode-sdk-go/internal/requestconfig"
"github.com/sst/opencode-sdk-go/option"
)
@@ -46,6 +47,14 @@ func (r *AppService) Init(ctx context.Context, opts ...option.RequestOption) (re
return
}
// Write a log entry to the server logs
func (r *AppService) Log(ctx context.Context, body AppLogParams, opts ...option.RequestOption) (res *bool, err error) {
opts = append(r.Options[:], opts...)
path := "log"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, body, &res, opts...)
return
}
type App struct {
Git bool `json:"git,required"`
Hostname string `json:"hostname,required"`
@@ -121,3 +130,54 @@ func (r *AppTime) UnmarshalJSON(data []byte) (err error) {
func (r appTimeJSON) RawJSON() string {
return r.raw
}
// Log level
type LogLevel string
const (
LogLevelDebug LogLevel = "DEBUG"
LogLevelInfo LogLevel = "INFO"
LogLevelWarn LogLevel = "WARN"
LogLevelError LogLevel = "ERROR"
)
func (r LogLevel) IsKnown() bool {
switch r {
case LogLevelDebug, LogLevelInfo, LogLevelWarn, LogLevelError:
return true
}
return false
}
type AppLogParams struct {
// Log level
Level param.Field[AppLogParamsLevel] `json:"level,required"`
// Log message
Message param.Field[string] `json:"message,required"`
// Service name for the log entry
Service param.Field[string] `json:"service,required"`
// Additional metadata for the log entry
Extra param.Field[map[string]interface{}] `json:"extra"`
}
func (r AppLogParams) MarshalJSON() (data []byte, err error) {
return apijson.MarshalRoot(r)
}
// Log level
type AppLogParamsLevel string
const (
AppLogParamsLevelDebug AppLogParamsLevel = "debug"
AppLogParamsLevelInfo AppLogParamsLevel = "info"
AppLogParamsLevelError AppLogParamsLevel = "error"
AppLogParamsLevelWarn AppLogParamsLevel = "warn"
)
func (r AppLogParamsLevel) IsKnown() bool {
switch r {
case AppLogParamsLevelDebug, AppLogParamsLevelInfo, AppLogParamsLevelError, AppLogParamsLevelWarn:
return true
}
return false
}
+29
View File
@@ -56,3 +56,32 @@ func TestAppInit(t *testing.T) {
t.Fatalf("err should be nil: %s", err.Error())
}
}
func TestAppLogWithOptionalParams(t *testing.T) {
t.Skip("skipped: tests are disabled for the time being")
baseURL := "http://localhost:4010"
if envURL, ok := os.LookupEnv("TEST_API_BASE_URL"); ok {
baseURL = envURL
}
if !testutil.CheckTestServer(t, baseURL) {
return
}
client := opencode.NewClient(
option.WithBaseURL(baseURL),
)
_, err := client.App.Log(context.TODO(), opencode.AppLogParams{
Level: opencode.F(opencode.AppLogParamsLevelDebug),
Message: opencode.F("message"),
Service: opencode.F("service"),
Extra: opencode.F(map[string]interface{}{
"foo": "bar",
}),
})
if err != nil {
var apierr *opencode.Error
if errors.As(err, &apierr) {
t.Log(string(apierr.DumpRequest(true)))
}
t.Fatalf("err should be nil: %s", err.Error())
}
}
+40 -37
View File
@@ -62,6 +62,8 @@ type Config struct {
Instructions []string `json:"instructions"`
// Custom keybind configurations
Keybinds Keybinds `json:"keybinds"`
// Minimum log level to write to log files
LogLevel LogLevel `json:"log_level"`
// MCP (Model Context Protocol) server configurations
Mcp map[string]ConfigMcp `json:"mcp"`
// Model to use in the format of provider/model, eg anthropic/claude-2
@@ -82,6 +84,7 @@ type configJSON struct {
Experimental apijson.Field
Instructions apijson.Field
Keybinds apijson.Field
LogLevel apijson.Field
Mcp apijson.Field
Model apijson.Field
Provider apijson.Field
@@ -396,71 +399,71 @@ func (r configProviderModelsLimitJSON) RawJSON() string {
type Keybinds struct {
// Exit the application
AppExit string `json:"app_exit"`
AppExit string `json:"app_exit,required"`
// Show help dialog
AppHelp string `json:"app_help"`
AppHelp string `json:"app_help,required"`
// Open external editor
EditorOpen string `json:"editor_open"`
EditorOpen string `json:"editor_open,required"`
// Close file
FileClose string `json:"file_close"`
// Toggle split/unified diff
FileDiffToggle string `json:"file_diff_toggle"`
FileClose string `json:"file_close,required"`
// Split/unified diff
FileDiffToggle string `json:"file_diff_toggle,required"`
// List files
FileList string `json:"file_list"`
FileList string `json:"file_list,required"`
// Search file
FileSearch string `json:"file_search"`
FileSearch string `json:"file_search,required"`
// Clear input field
InputClear string `json:"input_clear"`
InputClear string `json:"input_clear,required"`
// Insert newline in input
InputNewline string `json:"input_newline"`
InputNewline string `json:"input_newline,required"`
// Paste from clipboard
InputPaste string `json:"input_paste"`
InputPaste string `json:"input_paste,required"`
// Submit input
InputSubmit string `json:"input_submit"`
InputSubmit string `json:"input_submit,required"`
// Leader key for keybind combinations
Leader string `json:"leader"`
Leader string `json:"leader,required"`
// Copy message
MessagesCopy string `json:"messages_copy"`
MessagesCopy string `json:"messages_copy,required"`
// Navigate to first message
MessagesFirst string `json:"messages_first"`
MessagesFirst string `json:"messages_first,required"`
// Scroll messages down by half page
MessagesHalfPageDown string `json:"messages_half_page_down"`
MessagesHalfPageDown string `json:"messages_half_page_down,required"`
// Scroll messages up by half page
MessagesHalfPageUp string `json:"messages_half_page_up"`
MessagesHalfPageUp string `json:"messages_half_page_up,required"`
// Navigate to last message
MessagesLast string `json:"messages_last"`
MessagesLast string `json:"messages_last,required"`
// Toggle layout
MessagesLayoutToggle string `json:"messages_layout_toggle"`
MessagesLayoutToggle string `json:"messages_layout_toggle,required"`
// Navigate to next message
MessagesNext string `json:"messages_next"`
MessagesNext string `json:"messages_next,required"`
// Scroll messages down by one page
MessagesPageDown string `json:"messages_page_down"`
MessagesPageDown string `json:"messages_page_down,required"`
// Scroll messages up by one page
MessagesPageUp string `json:"messages_page_up"`
MessagesPageUp string `json:"messages_page_up,required"`
// Navigate to previous message
MessagesPrevious string `json:"messages_previous"`
MessagesPrevious string `json:"messages_previous,required"`
// Revert message
MessagesRevert string `json:"messages_revert"`
MessagesRevert string `json:"messages_revert,required"`
// List available models
ModelList string `json:"model_list"`
// Initialize project configuration
ProjectInit string `json:"project_init"`
// Toggle compact mode for session
SessionCompact string `json:"session_compact"`
ModelList string `json:"model_list,required"`
// Create/update AGENTS.md
ProjectInit string `json:"project_init,required"`
// Compact the session
SessionCompact string `json:"session_compact,required"`
// Interrupt current session
SessionInterrupt string `json:"session_interrupt"`
SessionInterrupt string `json:"session_interrupt,required"`
// List all sessions
SessionList string `json:"session_list"`
SessionList string `json:"session_list,required"`
// Create a new session
SessionNew string `json:"session_new"`
SessionNew string `json:"session_new,required"`
// Share current session
SessionShare string `json:"session_share"`
SessionShare string `json:"session_share,required"`
// Unshare current session
SessionUnshare string `json:"session_unshare"`
SessionUnshare string `json:"session_unshare,required"`
// List available themes
ThemeList string `json:"theme_list"`
// Show tool details
ToolDetails string `json:"tool_details"`
ThemeList string `json:"theme_list,required"`
// Toggle tool details
ToolDetails string `json:"tool_details,required"`
JSON keybindsJSON `json:"-"`
}
+4 -2
View File
@@ -916,14 +916,16 @@ func (r eventListResponseEventSessionErrorJSON) RawJSON() string {
func (r EventListResponseEventSessionError) implementsEventListResponse() {}
type EventListResponseEventSessionErrorProperties struct {
Error EventListResponseEventSessionErrorPropertiesError `json:"error"`
JSON eventListResponseEventSessionErrorPropertiesJSON `json:"-"`
Error EventListResponseEventSessionErrorPropertiesError `json:"error"`
SessionID string `json:"sessionID"`
JSON eventListResponseEventSessionErrorPropertiesJSON `json:"-"`
}
// eventListResponseEventSessionErrorPropertiesJSON contains the JSON metadata for
// the struct [EventListResponseEventSessionErrorProperties]
type eventListResponseEventSessionErrorPropertiesJSON struct {
Error apijson.Field
SessionID apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
+43 -44
View File
@@ -42,13 +42,55 @@ func (r *FileService) Read(ctx context.Context, query FileReadParams, opts ...op
}
// Get file status
func (r *FileService) Status(ctx context.Context, opts ...option.RequestOption) (res *[]FileStatusResponse, err error) {
func (r *FileService) Status(ctx context.Context, opts ...option.RequestOption) (res *[]File, err error) {
opts = append(r.Options[:], opts...)
path := "file/status"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return
}
type File struct {
Added int64 `json:"added,required"`
Path string `json:"path,required"`
Removed int64 `json:"removed,required"`
Status FileStatus `json:"status,required"`
JSON fileJSON `json:"-"`
}
// fileJSON contains the JSON metadata for the struct [File]
type fileJSON struct {
Added apijson.Field
Path apijson.Field
Removed apijson.Field
Status apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *File) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r fileJSON) RawJSON() string {
return r.raw
}
type FileStatus string
const (
FileStatusAdded FileStatus = "added"
FileStatusDeleted FileStatus = "deleted"
FileStatusModified FileStatus = "modified"
)
func (r FileStatus) IsKnown() bool {
switch r {
case FileStatusAdded, FileStatusDeleted, FileStatusModified:
return true
}
return false
}
type FileReadResponse struct {
Content string `json:"content,required"`
Type FileReadResponseType `json:"type,required"`
@@ -87,49 +129,6 @@ func (r FileReadResponseType) IsKnown() bool {
return false
}
type FileStatusResponse struct {
Added int64 `json:"added,required"`
File string `json:"file,required"`
Removed int64 `json:"removed,required"`
Status FileStatusResponseStatus `json:"status,required"`
JSON fileStatusResponseJSON `json:"-"`
}
// fileStatusResponseJSON contains the JSON metadata for the struct
// [FileStatusResponse]
type fileStatusResponseJSON struct {
Added apijson.Field
File apijson.Field
Removed apijson.Field
Status apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *FileStatusResponse) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r fileStatusResponseJSON) RawJSON() string {
return r.raw
}
type FileStatusResponseStatus string
const (
FileStatusResponseStatusAdded FileStatusResponseStatus = "added"
FileStatusResponseStatusDeleted FileStatusResponseStatus = "deleted"
FileStatusResponseStatusModified FileStatusResponseStatus = "modified"
)
func (r FileStatusResponseStatus) IsKnown() bool {
switch r {
case FileStatusResponseStatusAdded, FileStatusResponseStatusDeleted, FileStatusResponseStatusModified:
return true
}
return false
}
type FileReadParams struct {
Path param.Field[string] `query:"path,required"`
}
+159 -50
View File
@@ -42,7 +42,7 @@ func (r *FindService) Files(ctx context.Context, query FindFilesParams, opts ...
}
// Find workspace symbols
func (r *FindService) Symbols(ctx context.Context, query FindSymbolsParams, opts ...option.RequestOption) (res *[]FindSymbolsResponse, err error) {
func (r *FindService) Symbols(ctx context.Context, query FindSymbolsParams, opts ...option.RequestOption) (res *[]Symbol, err error) {
opts = append(r.Options[:], opts...)
path := "find/symbol"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
@@ -50,27 +50,24 @@ func (r *FindService) Symbols(ctx context.Context, query FindSymbolsParams, opts
}
// Find text in files
func (r *FindService) Text(ctx context.Context, query FindTextParams, opts ...option.RequestOption) (res *[]FindTextResponse, err error) {
func (r *FindService) Text(ctx context.Context, query FindTextParams, opts ...option.RequestOption) (res *[]Match, err error) {
opts = append(r.Options[:], opts...)
path := "find"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, query, &res, opts...)
return
}
type FindSymbolsResponse = interface{}
type FindTextResponse struct {
AbsoluteOffset float64 `json:"absolute_offset,required"`
LineNumber float64 `json:"line_number,required"`
Lines FindTextResponseLines `json:"lines,required"`
Path FindTextResponsePath `json:"path,required"`
Submatches []FindTextResponseSubmatch `json:"submatches,required"`
JSON findTextResponseJSON `json:"-"`
type Match struct {
AbsoluteOffset float64 `json:"absolute_offset,required"`
LineNumber float64 `json:"line_number,required"`
Lines MatchLines `json:"lines,required"`
Path MatchPath `json:"path,required"`
Submatches []MatchSubmatch `json:"submatches,required"`
JSON matchJSON `json:"-"`
}
// findTextResponseJSON contains the JSON metadata for the struct
// [FindTextResponse]
type findTextResponseJSON struct {
// matchJSON contains the JSON metadata for the struct [Match]
type matchJSON struct {
AbsoluteOffset apijson.Field
LineNumber apijson.Field
Lines apijson.Field
@@ -80,66 +77,63 @@ type findTextResponseJSON struct {
ExtraFields map[string]apijson.Field
}
func (r *FindTextResponse) UnmarshalJSON(data []byte) (err error) {
func (r *Match) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r findTextResponseJSON) RawJSON() string {
func (r matchJSON) RawJSON() string {
return r.raw
}
type FindTextResponseLines struct {
Text string `json:"text,required"`
JSON findTextResponseLinesJSON `json:"-"`
type MatchLines struct {
Text string `json:"text,required"`
JSON matchLinesJSON `json:"-"`
}
// findTextResponseLinesJSON contains the JSON metadata for the struct
// [FindTextResponseLines]
type findTextResponseLinesJSON struct {
// matchLinesJSON contains the JSON metadata for the struct [MatchLines]
type matchLinesJSON struct {
Text apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *FindTextResponseLines) UnmarshalJSON(data []byte) (err error) {
func (r *MatchLines) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r findTextResponseLinesJSON) RawJSON() string {
func (r matchLinesJSON) RawJSON() string {
return r.raw
}
type FindTextResponsePath struct {
Text string `json:"text,required"`
JSON findTextResponsePathJSON `json:"-"`
type MatchPath struct {
Text string `json:"text,required"`
JSON matchPathJSON `json:"-"`
}
// findTextResponsePathJSON contains the JSON metadata for the struct
// [FindTextResponsePath]
type findTextResponsePathJSON struct {
// matchPathJSON contains the JSON metadata for the struct [MatchPath]
type matchPathJSON struct {
Text apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *FindTextResponsePath) UnmarshalJSON(data []byte) (err error) {
func (r *MatchPath) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r findTextResponsePathJSON) RawJSON() string {
func (r matchPathJSON) RawJSON() string {
return r.raw
}
type FindTextResponseSubmatch struct {
End float64 `json:"end,required"`
Match FindTextResponseSubmatchesMatch `json:"match,required"`
Start float64 `json:"start,required"`
JSON findTextResponseSubmatchJSON `json:"-"`
type MatchSubmatch struct {
End float64 `json:"end,required"`
Match MatchSubmatchesMatch `json:"match,required"`
Start float64 `json:"start,required"`
JSON matchSubmatchJSON `json:"-"`
}
// findTextResponseSubmatchJSON contains the JSON metadata for the struct
// [FindTextResponseSubmatch]
type findTextResponseSubmatchJSON struct {
// matchSubmatchJSON contains the JSON metadata for the struct [MatchSubmatch]
type matchSubmatchJSON struct {
End apijson.Field
Match apijson.Field
Start apijson.Field
@@ -147,32 +141,147 @@ type findTextResponseSubmatchJSON struct {
ExtraFields map[string]apijson.Field
}
func (r *FindTextResponseSubmatch) UnmarshalJSON(data []byte) (err error) {
func (r *MatchSubmatch) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r findTextResponseSubmatchJSON) RawJSON() string {
func (r matchSubmatchJSON) RawJSON() string {
return r.raw
}
type FindTextResponseSubmatchesMatch struct {
Text string `json:"text,required"`
JSON findTextResponseSubmatchesMatchJSON `json:"-"`
type MatchSubmatchesMatch struct {
Text string `json:"text,required"`
JSON matchSubmatchesMatchJSON `json:"-"`
}
// findTextResponseSubmatchesMatchJSON contains the JSON metadata for the struct
// [FindTextResponseSubmatchesMatch]
type findTextResponseSubmatchesMatchJSON struct {
// matchSubmatchesMatchJSON contains the JSON metadata for the struct
// [MatchSubmatchesMatch]
type matchSubmatchesMatchJSON struct {
Text apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *FindTextResponseSubmatchesMatch) UnmarshalJSON(data []byte) (err error) {
func (r *MatchSubmatchesMatch) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r findTextResponseSubmatchesMatchJSON) RawJSON() string {
func (r matchSubmatchesMatchJSON) RawJSON() string {
return r.raw
}
type Symbol struct {
Kind float64 `json:"kind,required"`
Location SymbolLocation `json:"location,required"`
Name string `json:"name,required"`
JSON symbolJSON `json:"-"`
}
// symbolJSON contains the JSON metadata for the struct [Symbol]
type symbolJSON struct {
Kind apijson.Field
Location apijson.Field
Name apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *Symbol) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r symbolJSON) RawJSON() string {
return r.raw
}
type SymbolLocation struct {
Range SymbolLocationRange `json:"range,required"`
Uri string `json:"uri,required"`
JSON symbolLocationJSON `json:"-"`
}
// symbolLocationJSON contains the JSON metadata for the struct [SymbolLocation]
type symbolLocationJSON struct {
Range apijson.Field
Uri apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *SymbolLocation) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r symbolLocationJSON) RawJSON() string {
return r.raw
}
type SymbolLocationRange struct {
End SymbolLocationRangeEnd `json:"end,required"`
Start SymbolLocationRangeStart `json:"start,required"`
JSON symbolLocationRangeJSON `json:"-"`
}
// symbolLocationRangeJSON contains the JSON metadata for the struct
// [SymbolLocationRange]
type symbolLocationRangeJSON struct {
End apijson.Field
Start apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *SymbolLocationRange) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r symbolLocationRangeJSON) RawJSON() string {
return r.raw
}
type SymbolLocationRangeEnd struct {
Character float64 `json:"character,required"`
Line float64 `json:"line,required"`
JSON symbolLocationRangeEndJSON `json:"-"`
}
// symbolLocationRangeEndJSON contains the JSON metadata for the struct
// [SymbolLocationRangeEnd]
type symbolLocationRangeEndJSON struct {
Character apijson.Field
Line apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *SymbolLocationRangeEnd) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r symbolLocationRangeEndJSON) RawJSON() string {
return r.raw
}
type SymbolLocationRangeStart struct {
Character float64 `json:"character,required"`
Line float64 `json:"line,required"`
JSON symbolLocationRangeStartJSON `json:"-"`
}
// symbolLocationRangeStartJSON contains the JSON metadata for the struct
// [SymbolLocationRangeStart]
type symbolLocationRangeStartJSON struct {
Character apijson.Field
Line apijson.Field
raw string
ExtraFields map[string]apijson.Field
}
func (r *SymbolLocationRangeStart) UnmarshalJSON(data []byte) (err error) {
return apijson.UnmarshalRoot(data, r)
}
func (r symbolLocationRangeStartJSON) RawJSON() string {
return r.raw
}
@@ -29,7 +29,7 @@ func NewDecoder(res *http.Response) Decoder {
decoder = t(res.Body)
} else {
scn := bufio.NewScanner(res.Body)
scn.Buffer(nil, (bufio.MaxScanTokenSize<<4)*10)
scn.Buffer(nil, bufio.MaxScanTokenSize<<9)
decoder = &eventStreamDecoder{rc: res.Body, scn: scn}
}
return decoder
+2 -2
View File
@@ -7,5 +7,5 @@ cd "$(dirname "$0")/.."
echo "==> Running Go build"
go build .
# Compile the tests but don't run them
go test -c .
echo "==> Checking tests compile"
go test -run=^$ .
+21
View File
@@ -7,6 +7,7 @@ import theme from "toolbeam-docs-theme"
import config from "./config.mjs"
import { rehypeHeadingIds } from "@astrojs/markdown-remark"
import rehypeAutolinkHeadings from "rehype-autolink-headings"
import { spawnSync } from "child_process"
const github = "https://github.com/sst/opencode"
@@ -26,7 +27,9 @@ export default defineConfig({
markdown: {
rehypePlugins: [rehypeHeadingIds, [rehypeAutolinkHeadings, { behavior: "wrap" }]],
},
build: {},
integrations: [
configSchema(),
solidJs(),
starlight({
title: "opencode",
@@ -60,11 +63,14 @@ export default defineConfig({
"docs",
"docs/cli",
"docs/rules",
"docs/share",
"docs/config",
"docs/models",
"docs/themes",
"docs/keybinds",
"docs/enterprise",
"docs/mcp-servers",
"docs/troubleshooting",
],
components: {
Hero: "./src/components/Hero.astro",
@@ -78,4 +84,19 @@ export default defineConfig({
],
}),
],
redirects: {
"/discord": "https://discord.gg/opencode",
},
})
function configSchema() {
return {
name: "configSchema",
hooks: {
"astro:build:done": async () => {
console.log("generating config schema")
spawnSync("../opencode/script/schema.ts", ["./dist/config.json"])
},
},
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ export default {
: `https://${stage}.opencode.ai`,
socialCard: "https://social-cards.sst.dev",
github: "https://github.com/sst/opencode",
discord: "https://discord.gg/opencode",
discord: "https://opencode.ai/discord",
headerLinks: [
{ name: "Home", url: "/" },
{ name: "Docs", url: "/docs/" },
+1 -1
View File
@@ -30,7 +30,7 @@
"sharp": "0.32.5",
"shiki": "3.4.2",
"solid-js": "1.9.7",
"toolbeam-docs-theme": "0.4.1"
"toolbeam-docs-theme": "0.4.3"
},
"devDependencies": {
"opencode": "workspace:*",
-32
View File
@@ -1,32 +0,0 @@
import { type JSX, splitProps, createResource } from "solid-js"
import { codeToHtml } from "shiki"
import styles from "./codeblock.module.css"
import { transformerNotationDiff } from "@shikijs/transformers"
interface CodeBlockProps extends JSX.HTMLAttributes<HTMLDivElement> {
code: string
lang?: string
}
function CodeBlock(props: CodeBlockProps) {
const [local, rest] = splitProps(props, ["code", "lang"])
const [html] = createResource(
() => [local.code, local.lang],
async ([code, lang]) => {
// TODO: For testing delays
// await new Promise((resolve) => setTimeout(resolve, 3000))
return (await codeToHtml(code || "", {
lang: lang || "text",
themes: {
light: "github-light",
dark: "github-dark",
},
transformers: [transformerNotationDiff()],
})) as string
},
)
return <div innerHTML={html()} class={styles.codeblock} {...rest}></div>
}
export default CodeBlock
+40 -45
View File
@@ -1,13 +1,4 @@
import {
For,
Show,
onMount,
Suspense,
onCleanup,
createMemo,
createSignal,
SuspenseList,
} from "solid-js"
import { For, Show, onMount, Suspense, onCleanup, createMemo, createSignal, SuspenseList } from "solid-js"
import { DateTime } from "luxon"
import { createStore, reconcile } from "solid-js/store"
import { IconArrowDown } from "./icons"
@@ -277,7 +268,6 @@ export default function Share(props: {
}
}
}
console.log(result.messages)
return result
})
@@ -327,42 +317,47 @@ export default function Share(props: {
<div class={styles.parts}>
<SuspenseList revealOrder="forwards">
<For each={data().messages}>
{(msg, msgIndex) => (
<Suspense>
<For
each={msg.parts.filter((x, index) => {
if (x.type === "step-start" && index > 0) 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
})}
>
{(part, partIndex) => {
const last = createMemo(
() => data().messages.length === msgIndex() + 1 && msg.parts.length === partIndex() + 1,
)
{(msg, msgIndex) => {
const filteredParts = createMemo(() =>
msg.parts.filter((x, index) => {
if (x.type === "step-start" && index > 0) 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
})
)
onMount(() => {
const hash = window.location.hash.slice(1)
// Wait till all parts are loaded
if (
hash !== "" &&
!hasScrolledToAnchor &&
msg.parts.length === partIndex() + 1 &&
data().messages.length === msgIndex() + 1
) {
hasScrolledToAnchor = true
scrollToAnchor(hash)
}
})
return (
<Suspense>
<For each={filteredParts()}>
{(part, partIndex) => {
const last = createMemo(
() =>
data().messages.length === msgIndex() + 1 && filteredParts().length === partIndex() + 1,
)
return <Part last={last()} part={part} index={partIndex()} message={msg} />
}}
</For>
</Suspense>
)}
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">
@@ -1,10 +0,0 @@
.codeblock {
pre {
--shiki-dark-bg: var(--sl-color-bg-surface) !important;
background-color: var(--sl-color-bg-surface) !important;
span {
white-space: break-spaces;
}
}
}
@@ -127,3 +127,5 @@ The opencode CLI takes the following flags.
| `--help` | `-h` | Display help |
| `--version` | | Print version number |
| `--print-logs` | | Print logs to stderr |
| `--prompt` | `-p` | Prompt to use |
| `--model` | `-m` | Model to use in the form of provider/model |
@@ -63,6 +63,36 @@ You can configure the theme you want to use in your opencode config through the
---
### Logging
Logs are written to:
- **macOS/Linux**: `~/.local/share/opencode/log/`
- **Windows**: `%APPDATA%\opencode\log\`
You can configure the minimum log level through the `log_level` option.
```json title="opencode.json"
{
"$schema": "https://opencode.ai/config.json",
"log_level": "INFO"
}
```
With the following options:
| Level | Description |
| ----- | ----------- |
| `DEBUG` | All messages including debug information |
| `INFO` | Informational messages and above |
| `WARN` | Warnings and errors only |
| `ERROR` | Errors only |
The **default** log level is `INFO`. If you are running opencode locally in
development mode it's set to `DEBUG`.
---
### Keybinds
You can customize your keybinds through the `keybinds` option.
@@ -0,0 +1,63 @@
---
title: Enterprise
description: Using opencode in your organization.
---
opencode does not store any of your code or context data. This makes it easy for
you to use opencode at your organization.
To get started, we recommend:
1. Do a trial internally with your team.
2. [**Contact us**](mailto:hello@sst.dev) to discuss pricing and implementation options.
---
## Trial
Since opencode is open source and does not store any of your code or context data, your developers can simply [get started](/docs/) and carry out a trial.
---
### Data handling
**opencode does not store your code or context data.** All processing happens locally or through direct API calls to your AI provider.
The only caveat here is the optional `/share` feature that must be manually enabled.
---
#### Sharing conversations
If a user enables the `/share` feature, the conversation and the data associated with it are sent to the service we use to host these shares pages at opencode.ai.
The data is currently served through our CDN's edge network, and is cached on the edge near your users.
---
### Code ownership
**You own all code produced by opencode.** There are no licensing restrictions or ownership claims.
---
## Deployment
Once you have completed your trial and you are ready to self-host opencode at
your organization, you can [**contact us**](mailto:hello@sst.dev) to discuss
pricing and implementation options.
---
### SSO
SSO integration can be implemented for enterprise deployments after your trial. Currently users manage and configure individual API keys locally.
This can be switched to a centralized authentication system that your organization uses.
---
### Self-hosting
The share feature can be self-hosted and the share pages can be made accessible
only after the user has been authenticated.
@@ -0,0 +1,103 @@
---
title: Share
description: Share your opencode conversations.
---
opencode's share feature allows you to create public links to your opencode conversations, so you can collaborate with teammates or get help from others.
:::note
Shared conversations are publicly accessible to anyone with the link.
:::
---
## How it works
When you share a conversation, opencode:
1. Creates a unique public URL for your session
2. Syncs your conversation history to our servers
3. Makes the conversation accessible via the shareable link — `opencode.ai/s/<share-id>`
---
## Sharing
You can manually share a conversation or enable automatic sharing for all new conversations.
---
### Manual
Use the `/share` command in any conversation to create a shareable link:
```
/share
```
This will generate a unique URL that'll be copied to your clipboard.
---
### Autoshare
You can enable automatic sharing for all new conversations through the `autoshare` option in your [config file](/docs/config).
```json title="opencode.json"
{
"$schema": "https://opencode.ai/config.json",
"autoshare": true
}
```
By default, `autoshare` is disabled.
---
## Unsharing
To stop sharing a conversation and remove it from public access:
```
/unshare
```
This will remove the share link and delete the data related to the conversation.
---
## Privacy
There are a few things to keep in mind when sharing a conversation.
---
### Data retention
Shared conversations remain accessible until you explicitly unshare them. This
includes:
- Full conversation history
- All messages and responses
- Session metadata
---
### Recommendations
- Only share conversations that don't contain sensitive information
- Review conversation content before sharing
- Unshare conversations when collaboration is complete
- Avoid sharing conversations with proprietary code or confidential data
---
## For enterprises
For enterprise deployments, the share feature can be:
- **Self-hosted** on your own infrastructure
- **Restricted** to authenticated users only
- **Disabled** entirely for security compliance
[Learn more](/docs/enterprise) about using opencode in your organization.
@@ -0,0 +1,87 @@
---
title: Troubleshooting
description: Common issues and how to resolve them.
---
To debug any issues with opencode, you can check the logs or the session data
that it stores locally.
---
### Logs
Log files are written to:
- **macOS/Linux**: `~/.local/share/opencode/log/`
- **Windows**: `%APPDATA%\opencode\log\`
Log files are named with timestamps (e.g., `2025-01-09T123456.log`) and the most recent 10 log files are kept.
You can configure the log level in your [config file](/docs/config#logging) to get more detailed debug information.
---
### Storage
opencode stores session data and other application data on disk at:
- **macOS/Linux**: `~/.local/share/opencode/`
- **Windows**: `%APPDATA%\opencode\`
This directory contains:
- `auth.json` - Authentication data like API keys, OAuth tokens
- `log/` - Application logs
- `project/` - Project-specific data like session and message data
- If the project is within a Git repo, it is stored in `./<project-slug>/storage/`
- If it is not a Git repo, it is stored in `./global/storage/`
---
## Getting help
If you're experiencing issues with opencode:
1. **Report issues on GitHub**
The best way to report bugs or request features is through our GitHub repository:
[**github.com/sst/opencode/issues**](https://github.com/sst/opencode/issues)
Before creating a new issue, search existing issues to see if your problem has already been reported.
2. **Join our Discord**
For real-time help and community discussion, join our Discord server:
[**opencode.ai/discord**](https://opencode.ai/discord)
---
## Common issues
Here are some common issues and how to resolve them.
---
### opencode won't start
1. Check the logs for error messages
2. Try running with `--print-logs` to see output in the terminal
3. Ensure you have the latest version with `opencode upgrade`
---
### Authentication issues
1. Try re-authenticating with `opencode auth login <provider>`
2. Check that your API keys are valid
3. Ensure your network allows connections to the provider's API
---
### Model not available
1. Check that you've authenticated with the provider
2. Verify the model name in your config is correct
3. Some models may require specific access or subscriptions
+7
View File
@@ -48,17 +48,24 @@ resources:
app:
models:
app: App
logLevel: LogLevel
methods:
get: get /app
init: post /app/init
log: post /log
find:
models:
match: Match
symbol: Symbol
methods:
text: get /find
files: get /find/file
symbols: get /find/symbol
file:
models:
file: File
methods:
read: get /file
status: get /file/status