Skip to content

Commit ea0d19f

Browse files
committed
feat(opencode): add lightweight TUI (oclite) with raw ANSI terminal (#27)
1 parent de3d5cf commit ea0d19f

9 files changed

Lines changed: 617 additions & 0 deletions

File tree

‎packages/opencode/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
"typecheck": "tsgo --noEmit",
1010
"test": "bun test",
1111
"build": "bun run script/build.ts",
12+
"build:lite": "bun run script/build-lite.ts",
1213
"dev": "bun run --conditions=browser ./src/index.ts",
1314
"random": "echo 'Random script updated at $(date)' && echo 'Change queued successfully' && echo 'Another change made' && echo 'Yet another change' && echo 'One more change' && echo 'Final change' && echo 'Another final change' && echo 'Yet another final change'",
1415
"clean": "echo 'Cleaning up...' && rm -rf node_modules dist",
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#!/usr/bin/env bun
2+
import path from "path"
3+
import fs from "fs"
4+
import { $ } from "bun"
5+
6+
const ROOT = path.resolve(import.meta.dirname, "..")
7+
const DIST = path.join(ROOT, "dist", "oclite-darwin-arm64")
8+
const BIN = path.join(DIST, "bin")
9+
const HOME_BIN = path.join(process.env.HOME!, "bin")
10+
11+
async function build() {
12+
console.log("Building oclite...")
13+
14+
// Clean
15+
await fs.promises.rm(DIST, { recursive: true, force: true })
16+
await fs.promises.mkdir(BIN, { recursive: true })
17+
18+
// Build
19+
const result = await Bun.build({
20+
entrypoints: [path.join(ROOT, "src/cli/lite/index.ts")],
21+
outdir: BIN,
22+
target: "bun",
23+
minify: true,
24+
sourcemap: "none",
25+
naming: "oclite",
26+
})
27+
28+
if (!result.success) {
29+
console.error("Build failed:")
30+
for (const log of result.logs) {
31+
console.error(log)
32+
}
33+
process.exit(1)
34+
}
35+
36+
// Make executable
37+
await $`chmod +x ${path.join(BIN, "oclite")}`
38+
39+
// Copy to ~/bin
40+
await fs.promises.mkdir(HOME_BIN, { recursive: true })
41+
await fs.promises.copyFile(path.join(BIN, "oclite"), path.join(HOME_BIN, "oclite"))
42+
43+
// Sign for macOS
44+
await $`codesign --force --deep --sign - ${path.join(HOME_BIN, "oclite")}`.quiet().nothrow()
45+
await $`xattr -cr ${path.join(HOME_BIN, "oclite")}`.quiet().nothrow()
46+
47+
// Get size
48+
const stat = await fs.promises.stat(path.join(HOME_BIN, "oclite"))
49+
const sizeMB = (stat.size / 1024 / 1024).toFixed(2)
50+
51+
console.log(`✓ Built oclite (${sizeMB} MB)`)
52+
console.log(`✓ Installed to ~/bin/oclite`)
53+
console.log("\nRun with: ~/bin/oclite")
54+
}
55+
56+
build().catch((err) => {
57+
console.error(err)
58+
process.exit(1)
59+
})
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
#!/usr/bin/env bun
2+
import { cursor, clear, fg, style, write, screen } from "./terminal"
3+
import { parseKey, LineEditor } from "./input"
4+
import { Spinner } from "./spinner"
5+
import { chat } from "./session"
6+
7+
const PROMPT = `${fg.cyan}>${style.reset} `
8+
9+
async function main() {
10+
// Check TTY
11+
if (!process.stdin.isTTY) {
12+
console.error("oclite requires a TTY")
13+
process.exit(1)
14+
}
15+
16+
// Setup
17+
write(screen.alt)
18+
write(clear.screen)
19+
write(cursor.home)
20+
21+
// Header
22+
write(`${fg.brightCyan}${style.bold}oclite${style.reset} ${fg.gray}v0.1.0${style.reset}\n`)
23+
write(`${fg.gray}Type /help for commands, Ctrl+C to exit${style.reset}\n\n`)
24+
25+
// Input setup
26+
const editor = new LineEditor()
27+
process.stdin.setRawMode(true)
28+
process.stdin.resume()
29+
30+
// Render prompt
31+
editor.render(PROMPT)
32+
33+
// Handle input
34+
process.stdin.on("data", async (data: Buffer) => {
35+
const key = parseKey(data)
36+
37+
// Ctrl+C to exit
38+
if (key.ctrl && key.name === "c") {
39+
cleanup()
40+
process.exit(0)
41+
}
42+
43+
const result = editor.handle(key)
44+
45+
if (result !== null) {
46+
write("\n")
47+
48+
if (result.startsWith("/")) {
49+
handleCommand(result)
50+
} else if (result.trim()) {
51+
await handleMessage(result)
52+
}
53+
54+
editor.render(PROMPT)
55+
} else {
56+
editor.render(PROMPT)
57+
}
58+
})
59+
60+
// Cleanup on exit
61+
function cleanup() {
62+
write(cursor.show)
63+
write(screen.main)
64+
process.stdin.setRawMode(false)
65+
}
66+
67+
process.on("exit", cleanup)
68+
process.on("SIGINT", () => {
69+
cleanup()
70+
process.exit(0)
71+
})
72+
}
73+
74+
function handleCommand(cmd: string) {
75+
const command = cmd.slice(1).toLowerCase().trim()
76+
77+
if (command === "help") {
78+
write(`${fg.yellow}Commands:${style.reset}\n`)
79+
write(` /help - Show this help\n`)
80+
write(` /clear - Clear screen\n`)
81+
write(` /quit - Exit oclite\n`)
82+
write("\n")
83+
return
84+
}
85+
86+
if (command === "clear") {
87+
write(clear.screen)
88+
write(cursor.home)
89+
write(`${fg.brightCyan}${style.bold}oclite${style.reset} ${fg.gray}v0.1.0${style.reset}\n\n`)
90+
return
91+
}
92+
93+
if (command === "quit" || command === "exit") {
94+
process.exit(0)
95+
}
96+
97+
write(`${fg.red}Unknown command: ${cmd}${style.reset}\n\n`)
98+
}
99+
100+
async function handleMessage(message: string) {
101+
const spinner = new Spinner("Thinking")
102+
spinner.start()
103+
104+
let first = true
105+
try {
106+
for await (const chunk of chat(message)) {
107+
if (first) {
108+
spinner.stop(true)
109+
first = false
110+
}
111+
112+
if (chunk.type === "text" && chunk.content) {
113+
write(chunk.content)
114+
}
115+
116+
if (chunk.type === "tool_start" && chunk.tool) {
117+
write(`\n${fg.yellow}▶ ${chunk.tool}${style.reset}\n`)
118+
}
119+
120+
if (chunk.type === "tool_end" && chunk.tool) {
121+
write(`${fg.green}✓ ${chunk.tool}${style.reset}\n`)
122+
}
123+
124+
if (chunk.type === "error" && chunk.content) {
125+
write(`\n${fg.red}Error: ${chunk.content}${style.reset}\n`)
126+
}
127+
}
128+
} catch (err) {
129+
if (first) spinner.stop(false)
130+
const msg = err instanceof Error ? err.message : String(err)
131+
write(`\n${fg.red}Error: ${msg}${style.reset}\n`)
132+
}
133+
134+
write("\n")
135+
}
136+
137+
main().catch(console.error)
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import { cursor, write } from "./terminal"
2+
3+
export interface Key {
4+
name: string
5+
char?: string
6+
ctrl?: boolean
7+
meta?: boolean
8+
}
9+
10+
export function parseKey(data: Buffer): Key {
11+
const s = data.toString()
12+
13+
// Control characters
14+
if (s === "\x03") return { name: "c", ctrl: true }
15+
if (s === "\x04") return { name: "d", ctrl: true }
16+
if (s === "\x0c") return { name: "l", ctrl: true }
17+
18+
// Special keys
19+
if (s === "\r" || s === "\n") return { name: "return" }
20+
if (s === "\x7f" || s === "\b") return { name: "backspace" }
21+
if (s === "\t") return { name: "tab" }
22+
if (s === "\x1b") return { name: "escape" }
23+
24+
// Arrow keys
25+
if (s === "\x1b[A") return { name: "up" }
26+
if (s === "\x1b[B") return { name: "down" }
27+
if (s === "\x1b[C") return { name: "right" }
28+
if (s === "\x1b[D") return { name: "left" }
29+
30+
// Home/End
31+
if (s === "\x1b[H" || s === "\x1b[1~") return { name: "home" }
32+
if (s === "\x1b[F" || s === "\x1b[4~") return { name: "end" }
33+
34+
// Delete
35+
if (s === "\x1b[3~") return { name: "delete" }
36+
37+
// Regular character
38+
if (s.length === 1 && s >= " ") return { name: "char", char: s }
39+
40+
return { name: "unknown", char: s }
41+
}
42+
43+
export class LineEditor {
44+
line = ""
45+
cursor = 0
46+
history: string[] = []
47+
historyIndex = -1
48+
49+
render(prompt: string) {
50+
write(`\r${prompt}${this.line}${" ".repeat(10)}\r${prompt}`)
51+
if (this.cursor > 0) {
52+
write(cursor.forward(this.cursor))
53+
}
54+
}
55+
56+
handle(key: Key): string | null {
57+
if (key.name === "return") {
58+
const result = this.line
59+
if (result.trim()) {
60+
this.history.push(result)
61+
}
62+
this.line = ""
63+
this.cursor = 0
64+
this.historyIndex = -1
65+
return result
66+
}
67+
68+
if (key.name === "backspace" && this.cursor > 0) {
69+
this.line = this.line.slice(0, this.cursor - 1) + this.line.slice(this.cursor)
70+
this.cursor--
71+
}
72+
73+
if (key.name === "delete" && this.cursor < this.line.length) {
74+
this.line = this.line.slice(0, this.cursor) + this.line.slice(this.cursor + 1)
75+
}
76+
77+
if (key.name === "left" && this.cursor > 0) {
78+
this.cursor--
79+
}
80+
81+
if (key.name === "right" && this.cursor < this.line.length) {
82+
this.cursor++
83+
}
84+
85+
if (key.name === "home") {
86+
this.cursor = 0
87+
}
88+
89+
if (key.name === "end") {
90+
this.cursor = this.line.length
91+
}
92+
93+
if (key.name === "up" && this.history.length > 0) {
94+
if (this.historyIndex < this.history.length - 1) {
95+
this.historyIndex++
96+
this.line = this.history[this.history.length - 1 - this.historyIndex]
97+
this.cursor = this.line.length
98+
}
99+
}
100+
101+
if (key.name === "down") {
102+
if (this.historyIndex > 0) {
103+
this.historyIndex--
104+
this.line = this.history[this.history.length - 1 - this.historyIndex]
105+
this.cursor = this.line.length
106+
} else if (this.historyIndex === 0) {
107+
this.historyIndex = -1
108+
this.line = ""
109+
this.cursor = 0
110+
}
111+
}
112+
113+
if (key.name === "char" && key.char) {
114+
this.line = this.line.slice(0, this.cursor) + key.char + this.line.slice(this.cursor)
115+
this.cursor++
116+
}
117+
118+
// Ctrl+L to clear
119+
if (key.ctrl && key.name === "l") {
120+
return "/clear"
121+
}
122+
123+
return null
124+
}
125+
}

0 commit comments

Comments
 (0)