feat: add opentui interface for opencode

- Add comprehensive TUI interface with React Ink components
- Implement session management, model selection, and command dialogs
- Add theme system with customizable colors and styling
- Integrate with existing opencode server and SDK
- Add todo management and file browsing capabilities
- Include proper TypeScript support and error handling
This commit is contained in:
Dax Raad
2025-09-19 17:21:04 -04:00
parent f1cbdf441c
commit 02848a350c
69 changed files with 3240 additions and 349 deletions
+11
View File
@@ -0,0 +1,11 @@
import { createOpencodeClient, createOpencodeServer } from "../src/index"
const client = createOpencodeClient({
baseUrl: "http://localhost:4096",
})
await client.event.subscribe().then(async (event) => {
for await (const e of event.stream) {
console.log(e)
}
})
+1 -2
View File
@@ -29,10 +29,9 @@
],
"devDependencies": {
"typescript": "catalog:",
"@hey-api/openapi-ts": "0.80.1",
"@tsconfig/node22": "catalog:"
},
"dependencies": {
"@hey-api/openapi-ts": "0.81.0"
"@hey-api/openapi-ts": "0.82.5"
}
}
+2
View File
@@ -10,6 +10,8 @@ import { createClient } from "@hey-api/openapi-ts"
await $`bun dev generate > ${dir}/openapi.json`.cwd(path.resolve(dir, "../../opencode"))
await $`rm -rf src/gen`
await createClient({
input: "./openapi.json",
output: {
+68 -30
View File
@@ -1,6 +1,8 @@
// This file is auto-generated by @hey-api/openapi-ts
import { createSseClient } from "../core/serverSentEvents.gen.js"
import type { HttpMethod } from "../core/types.gen.js"
import { getValidRequestBody } from "../core/utils.gen.js"
import type { Client, Config, RequestOptions, ResolvedRequestOptions } from "./types.gen.js"
import {
buildUrl,
@@ -49,12 +51,12 @@ export const createClient = (config: Config = {}): Client => {
await opts.requestValidator(opts)
}
if (opts.body && opts.bodySerializer) {
if (opts.body !== undefined && opts.bodySerializer) {
opts.serializedBody = opts.bodySerializer(opts.body)
}
// remove Content-Type header if body is empty to avoid sending invalid requests
if (opts.serializedBody === undefined || opts.serializedBody === "") {
if (opts.body === undefined || opts.serializedBody === "") {
opts.headers.delete("Content-Type")
}
@@ -69,7 +71,7 @@ export const createClient = (config: Config = {}): Client => {
const requestInit: ReqInit = {
redirect: "follow",
...opts,
body: opts.serializedBody,
body: getValidRequestBody(opts),
}
let request = new Request(url, requestInit)
@@ -97,18 +99,36 @@ export const createClient = (config: Config = {}): Client => {
}
if (response.ok) {
const parseAs =
(opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json"
if (response.status === 204 || response.headers.get("Content-Length") === "0") {
let emptyData: any
switch (parseAs) {
case "arrayBuffer":
case "blob":
case "text":
emptyData = await response[parseAs]()
break
case "formData":
emptyData = new FormData()
break
case "stream":
emptyData = response.body
break
case "json":
default:
emptyData = {}
break
}
return opts.responseStyle === "data"
? {}
? emptyData
: {
data: {},
data: emptyData,
...result,
}
}
const parseAs =
(opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json"
let data: any
switch (parseAs) {
case "arrayBuffer":
@@ -178,35 +198,53 @@ export const createClient = (config: Config = {}): Client => {
}
}
const makeMethod = (method: Required<Config>["method"]) => {
const fn = (options: RequestOptions) => request({ ...options, method })
fn.sse = async (options: RequestOptions) => {
const { opts, url } = await beforeRequest(options)
return createSseClient({
...opts,
body: opts.body as BodyInit | null | undefined,
headers: opts.headers as unknown as Record<string, string>,
method,
url,
})
}
return fn
const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) => request({ ...options, method })
const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
const { opts, url } = await beforeRequest(options)
return createSseClient({
...opts,
body: opts.body as BodyInit | null | undefined,
headers: opts.headers as unknown as Record<string, string>,
method,
onRequest: async (url, init) => {
let request = new Request(url, init)
for (const fn of interceptors.request._fns) {
if (fn) {
request = await fn(request, opts)
}
}
return request
},
url,
})
}
return {
buildUrl,
connect: makeMethod("CONNECT"),
delete: makeMethod("DELETE"),
get: makeMethod("GET"),
connect: makeMethodFn("CONNECT"),
delete: makeMethodFn("DELETE"),
get: makeMethodFn("GET"),
getConfig,
head: makeMethod("HEAD"),
head: makeMethodFn("HEAD"),
interceptors,
options: makeMethod("OPTIONS"),
patch: makeMethod("PATCH"),
post: makeMethod("POST"),
put: makeMethod("PUT"),
options: makeMethodFn("OPTIONS"),
patch: makeMethodFn("PATCH"),
post: makeMethodFn("POST"),
put: makeMethodFn("PUT"),
request,
setConfig,
trace: makeMethod("TRACE"),
sse: {
connect: makeSseFn("CONNECT"),
delete: makeSseFn("DELETE"),
get: makeSseFn("GET"),
head: makeSseFn("HEAD"),
options: makeSseFn("OPTIONS"),
patch: makeSseFn("PATCH"),
post: makeSseFn("POST"),
put: makeSseFn("PUT"),
trace: makeSseFn("TRACE"),
},
trace: makeMethodFn("TRACE"),
} as Client
}
+4 -8
View File
@@ -20,7 +20,7 @@ export interface Config<T extends ClientOptions = ClientOptions>
*
* @default globalThis.fetch
*/
fetch?: (request: Request) => ReturnType<typeof fetch>
fetch?: typeof fetch
/**
* Please don't use the Fetch client for Next.js applications. The `next`
* options won't have any effect.
@@ -128,7 +128,7 @@ export interface ClientOptions {
throwOnError?: boolean
}
type MethodFnBase = <
type MethodFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
@@ -137,7 +137,7 @@ type MethodFnBase = <
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">,
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>
type MethodFnServerSentEvents = <
type SseFn = <
TData = unknown,
TError = unknown,
ThrowOnError extends boolean = false,
@@ -146,10 +146,6 @@ type MethodFnServerSentEvents = <
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, "method">,
) => Promise<ServerSentEventsResult<TData, TError>>
type MethodFn = MethodFnBase & {
sse: MethodFnServerSentEvents
}
type RequestFn = <
TData = unknown,
TError = unknown,
@@ -171,7 +167,7 @@ type BuildUrlFn = <
options: Pick<TData, "url"> & Options<TData>,
) => string
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn> & {
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>
}
+10 -2
View File
@@ -162,14 +162,22 @@ export const mergeConfigs = (a: Config, b: Config): Config => {
return config
}
const headersEntries = (headers: Headers): Array<[string, string]> => {
const entries: Array<[string, string]> = []
headers.forEach((value, key) => {
entries.push([key, value])
})
return entries
}
export const mergeHeaders = (...headers: Array<Required<Config>["headers"] | undefined>): Headers => {
const mergedHeaders = new Headers()
for (const header of headers) {
if (!header || typeof header !== "object") {
if (!header) {
continue
}
const iterator = header instanceof Headers ? header.entries() : Object.entries(header)
const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header)
for (const [key, value] of iterator) {
if (value === null) {
@@ -4,6 +4,17 @@ import type { Config } from "./types.gen.js"
export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method"> &
Pick<Config, "method" | "responseTransformer" | "responseValidator"> & {
/**
* Fetch API implementation. You can use this option to provide a custom
* fetch instance.
*
* @default globalThis.fetch
*/
fetch?: typeof fetch
/**
* Implementing clients can call request interceptors inside this hook.
*/
onRequest?: (url: string, init: RequestInit) => Promise<Request>
/**
* Callback invoked when a network or parsing error occurs during streaming.
*
@@ -21,6 +32,7 @@ export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, "method
* @returns Nothing (void).
*/
onSseEvent?: (event: StreamEvent<TData>) => void
serializedBody?: RequestInit["body"]
/**
* Default retry delay in milliseconds.
*
@@ -64,6 +76,7 @@ export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unkn
}
export const createSseClient = <TData = unknown>({
onRequest,
onSseError,
onSseEvent,
responseTransformer,
@@ -99,7 +112,21 @@ export const createSseClient = <TData = unknown>({
}
try {
const response = await fetch(url, { ...options, headers, signal })
const requestInit: RequestInit = {
redirect: "follow",
...options,
body: options.serializedBody,
headers,
signal,
}
let request = new Request(url, requestInit)
if (onRequest) {
request = await onRequest(url, requestInit)
}
// fetch must be assigned here, otherwise it would throw the error:
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const _fetch = options.fetch ?? globalThis.fetch
const response = await _fetch(request)
if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`)
+7 -12
View File
@@ -3,24 +3,19 @@
import type { Auth, AuthToken } from "./auth.gen.js"
import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from "./bodySerializer.gen.js"
export interface Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never> {
export type HttpMethod = "connect" | "delete" | "get" | "head" | "options" | "patch" | "post" | "put" | "trace"
export type Client<RequestFn = never, Config = unknown, MethodFn = never, BuildUrlFn = never, SseFn = never> = {
/**
* Returns the final request URL.
*/
buildUrl: BuildUrlFn
connect: MethodFn
delete: MethodFn
get: MethodFn
getConfig: () => Config
head: MethodFn
options: MethodFn
patch: MethodFn
post: MethodFn
put: MethodFn
request: RequestFn
setConfig: (config: Config) => Config
trace: MethodFn
}
} & {
[K in HttpMethod]: MethodFn
} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } })
export interface Config {
/**
@@ -47,7 +42,7 @@ export interface Config {
*
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
*/
method?: "CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE"
method?: Uppercase<HttpMethod>
/**
* A function for serializing request query parameters. By default, arrays
* will be exploded in form style, objects will be exploded in deepObject
+29 -1
View File
@@ -1,6 +1,6 @@
// This file is auto-generated by @hey-api/openapi-ts
import type { QuerySerializer } from "./bodySerializer.gen.js"
import type { BodySerializer, QuerySerializer } from "./bodySerializer.gen.js"
import {
type ArraySeparatorStyle,
serializeArrayParam,
@@ -107,3 +107,31 @@ export const getUrl = ({
}
return url
}
export function getValidRequestBody(options: {
body?: unknown
bodySerializer?: BodySerializer | null
serializedBody?: unknown
}) {
const hasBody = options.body !== undefined
const isSerializedBody = hasBody && options.bodySerializer
if (isSerializedBody) {
if ("serializedBody" in options) {
const hasSerializedBody = options.serializedBody !== undefined && options.serializedBody !== ""
return hasSerializedBody ? options.serializedBody : null
}
// not all clients implement a serializedBody property (i.e. client-axios)
return options.body !== "" ? options.body : null
}
// plain/text body
if (hasBody) {
return options.body
}
// no body was provided
return undefined
}
+13 -1
View File
@@ -29,6 +29,8 @@ import type {
SessionUpdateResponses,
SessionChildrenData,
SessionChildrenResponses,
SessionTodoData,
SessionTodoResponses,
SessionInitData,
SessionInitResponses,
SessionAbortData,
@@ -275,6 +277,16 @@ class Session extends _HeyApiClient {
})
}
/**
* Get the todo list for a session
*/
public todo<ThrowOnError extends boolean = false>(options: Options<SessionTodoData, ThrowOnError>) {
return (options.client ?? this._client).get<SessionTodoResponses, unknown, ThrowOnError>({
url: "/session/{id}/todo",
...options,
})
}
/**
* Analyze the app and create an AGENTS.md file
*/
@@ -647,7 +659,7 @@ class Event extends _HeyApiClient {
* Get events
*/
public subscribe<ThrowOnError extends boolean = false>(options?: Options<EventSubscribeData, ThrowOnError>) {
return (options?.client ?? this._client).get.sse<EventSubscribeResponses, unknown, ThrowOnError>({
return (options?.client ?? this._client).sse.get<EventSubscribeResponses, unknown, ThrowOnError>({
url: "/event",
...options,
})
+58 -1
View File
@@ -550,6 +550,25 @@ export type Session = {
}
}
export type Todo = {
/**
* Brief description of the task
*/
content: string
/**
* Current status of the task: pending, in_progress, completed, cancelled
*/
status: string
/**
* Priority level of the task: high, medium, low
*/
priority: string
/**
* Unique identifier for the todo item
*/
id: string
}
export type UserMessage = {
id: string
sessionID: string
@@ -695,11 +714,17 @@ export type FilePart = {
export type ToolStatePending = {
status: "pending"
raw: string
input: {
[key: string]: unknown
}
}
export type ToolStateRunning = {
status: "running"
input: unknown
input: {
[key: string]: unknown
}
title?: string
metadata?: {
[key: string]: unknown
@@ -1076,6 +1101,14 @@ export type EventFileEdited = {
}
}
export type EventTodoUpdated = {
type: "todo.updated"
properties: {
sessionID: string
todos: Array<Todo>
}
}
export type EventSessionIdle = {
type: "session.idle"
properties: {
@@ -1138,6 +1171,7 @@ export type Event =
| EventPermissionUpdated
| EventPermissionReplied
| EventFileEdited
| EventTodoUpdated
| EventSessionIdle
| EventSessionUpdated
| EventSessionDeleted
@@ -1404,6 +1438,29 @@ export type SessionChildrenResponses = {
export type SessionChildrenResponse = SessionChildrenResponses[keyof SessionChildrenResponses]
export type SessionTodoData = {
body?: never
path: {
/**
* Session ID
*/
id: string
}
query?: {
directory?: string
}
url: "/session/{id}/todo"
}
export type SessionTodoResponses = {
/**
* Todo list
*/
200: Array<Todo>
}
export type SessionTodoResponse = SessionTodoResponses[keyof SessionTodoResponses]
export type SessionInitData = {
body?: {
messageID: string
+2 -1
View File
@@ -9,5 +9,6 @@
"lib": ["es2022", "dom", "dom.iterable"],
"customConditions": ["development"]
},
"include": ["src"]
"include": ["src"],
"exclude": ["src/gen"]
}