한국어
문서
OpenCode에서 빌드하기
플러그인
TUI 플러그인

TUI 플러그인 개발

@opencode/plugin/tui를 사용하여 터미널 UI용 OpenCode 플러그인의 TUI 파트를 개발합니다.

TUI 플러그인은 명령어, 라우트, 슬롯, Markdown 렌더러, 알림 및 로컬 상태로 터미널 UI를 확장합니다. TUI 플러그인은 보통 서버 파트와 함께 구성되는 플러그인 패키지의 ./tui 파트입니다.

src/tui.tsx
import { Plugin } from "@opencode/plugin/tui"
 
export default Plugin.define({
  id: "acme.cli",
  setup(context) {
    context.ui.toast.show({ message: "TUI plugin loaded", variant: "success" })
  },
})

@opencode/plugin/tui를 직접 import하세요. OpenCode가 런타임에 이 import를 해석하므로 로컬 TUI 플러그인에 OpenCode 체크아웃의 절대 경로가 필요하지 않습니다.

컨텍스트

setup은 설정, 앱 메타데이터, 현재 위치, OpenCode 클라이언트, 캐시된 데이터, 테마 토큰, OpenTUI 렌더러 및 아래에 문서화된 UI API를 받습니다.

setup(context) {
  const compact = context.options.compact === true
  const location = context.location ?? context.data.location.default()
  const version = context.app.version
  const channel = context.app.channel
  const client = context.client
  const renderer = context.renderer
  const theme = context.theme
}

플러그인이 소유한 리소스에 대해서는 정리(cleanup) 함수를 반환하세요.

setup(context) {
  const stop = context.data.on("session.execution.succeeded", () => {})
  return () => stop()
}

클라이언트

context.client는 생성된 OpenCode 클라이언트이며 원격 서버를 포함해 연결된 서버를 호출할 수 있습니다.

const response = await context.client.plugin.list({
  location: context.location ?? context.data.location.default(),
})
const plugins = response.data

이벤트

특정 타입의 이벤트 하나를 구독하려면 data.on을, 모든 서버 이벤트를 구독하려면 data.listen을 사용하세요. 둘 다 구독 해제 함수를 반환합니다.

const stopPermission = context.data.on("permission.asked", (event) => {
  context.ui.toast.show({ message: `Permission ${event.data.id}` })
})
const stopAll = context.data.listen(({ details }) => console.log(details.type))
 
return () => {
  stopPermission()
  stopAll()
}

세션

세션 데이터는 목록 조회, 단건 조회, 계층 구조, 비용, 상태, 동기화 및 무효화 기능을 제공합니다.

const sessions = context.data.session.list()
const session = context.data.session.get(sessionID)
const rootID = context.data.session.root(sessionID)
const familyIDs = context.data.session.family(sessionID)
const cost = context.data.session.cost(sessionID)
const status = context.data.session.status(sessionID)
await context.data.session.sync(sessionID)
context.data.session.invalidate(sessionID)

대기 중인 수신함 항목(pending inbox items)과 메시지도 목록, 조회, 동기화 및 무효화 API를 제공합니다.

await context.data.session.pending.sync(sessionID)
const pending = context.data.session.pending.list(sessionID)
context.data.session.pending.invalidate(sessionID)
 
await context.data.session.message.sync(sessionID)
const messages = context.data.session.message.list(sessionID)
const message = context.data.session.message.get(sessionID, messageID)
context.data.session.message.invalidate(sessionID)

세션의 권한 요청을 읽고 새로 고칠 수 있습니다.

await context.data.session.permission.sync(sessionID)
const requests = context.data.session.permission.list(sessionID) ?? []
context.data.session.permission.invalidate(sessionID)

특정 위치에서 폼(form)을 나열, 새로 고침, 응답 또는 취소할 수 있습니다.

import type { SessionFormCancelInput, SessionFormReplyInput } from "@opencode/client"
 
async function handleForm(reply: SessionFormReplyInput, cancel: SessionFormCancelInput) {
  const location = context.location
  await context.data.session.form.sync(sessionID, location)
  const forms = context.data.session.form.list(sessionID, location) ?? []
  await context.data.session.form.reply(reply, location)
  await context.data.session.form.cancel(cancel, location)
  context.data.session.form.invalidate(sessionID, location)
}

프로젝트 및 셸

프로젝트와 저장된 권한은 목록, 조회, 동기화 및 무효화 작업을 지원합니다.

await context.data.project.sync()
const projects = context.data.project.list()
const project = context.data.project.get(projectID)
context.data.project.invalidate()
 
await context.data.project.permission.sync(projectID)
const saved = context.data.project.permission.list(projectID) ?? []
context.data.project.permission.invalidate(projectID)

셸 데이터는 위치 범위의 목록, 조회, 동기화 및 무효화 작업을 지원합니다.

await context.data.shell.sync(context.location)
const shells = context.data.shell.list(context.location)
const shell = context.data.shell.get(shellID)
context.data.shell.invalidate(context.location)

위치 데이터

위치 상태는 기본 위치와 새로 고침 제어 기능을 노출합니다.

const location = context.data.location.default()
await context.data.location.sync(location)
context.data.location.invalidate(location)

버전 관리 상태는 특정 위치의 저장소 정보를 노출합니다.

await context.data.location.vcs.sync(context.location)
const vcs = context.data.location.vcs.info(context.location)
const branch = vcs?.branch.current
context.data.location.vcs.invalidate(context.location)

에이전트, 명령어, 통합 기능, 모델, 프로바이더, 레퍼런스, 스킬 및 MCP 데이터는 공통적으로 list, sync, invalidate 메서드를 제공합니다.

const location = context.location
await Promise.all([
  context.data.location.agent.sync(location),
  context.data.location.command.sync(location),
  context.data.location.integration.sync(location),
  context.data.location.model.sync(location),
  context.data.location.provider.sync(location),
  context.data.location.reference.sync(location),
  context.data.location.skill.sync(location),
  context.data.location.mcp.server.sync(location),
  context.data.location.mcp.resource.sync(location),
])
 
const agents = context.data.location.agent.list(location) ?? []
const commands = context.data.location.command.list(location) ?? []
const integrations = context.data.location.integration.list(location) ?? []
const models = context.data.location.model.list(location) ?? []
const providers = context.data.location.provider.list(location) ?? []
const references = context.data.location.reference.list(location) ?? []
const skills = context.data.location.skill.list(location) ?? []
const servers = context.data.location.mcp.server.list(location) ?? []
const resources = context.data.location.mcp.resource.list(location) ?? []
 
context.data.location.model.invalidate(location)

알림(Attention)

알림 요청은 터미널 포커스 상태에 따라 시스템 알림을 표시하거나, 설정된 사운드를 재생하거나, 둘 다 수행할 수 있습니다.

const result = await context.attention.notify({
  title: "OpenCode",
  message: "Session done",
  notification: { when: "blurred" },
  sound: { name: "done", volume: 0.5, when: "always" },
})
console.log(result.ok, result.notification, result.sound, result.skipped)

테마 및 렌더러

OpenTUI 요소와 함께 의미적 테마 토큰을 사용하고, 렌더러 전용 헬퍼에는 context.renderer를 전달하세요.

const Status = () => <text fg={context.theme.text.base}>Ready</text>
const renderer = context.renderer

렌더러가 그리는 OpenTUI 리소스에는 소유자로 context.renderer.nativeScene이 필요합니다. 예를 들어 <markdown>과 <code>에는 SyntaxStyle이 필요합니다. 리소스를 그리는 마지막 프레임이 끝난 뒤 렌더러가 유휴 상태(idle)일 때 리소스를 파괴(destroy)하세요.

import { SyntaxStyle } from "@opentui/core"
 
const style = SyntaxStyle.fromStyles({ default: { fg: context.theme.text.base } }, context.renderer.nativeScene)
context.ui.slot({ append: "home.footer", render: () => <markdown content="Ready" syntaxStyle={style} /> })
return () => context.renderer.idle().then(() => style.destroy())

렌더러블(renderable)의 레이아웃 스타일을 읽으려면 box.getPadding(Yoga.Edge.Bottom) 또는 box.getMaxWidth()처럼 Yoga Node 게터 이름과 동일한 메서드를 호출하세요. 호스트 렌더러블은 플러그인 API의 일부가 아니므로 구조와 스타일이 모든 릴리스에서 변경될 수 있습니다.

OpenTUI 0.5용으로 빌드된 플러그인

OpenCode는 내장된 자체 OpenTUI로 플러그인을 실행합니다. OpenTUI 0.6부터 다음 사항이 변경되었습니다.

  • SyntaxStyle.create(), SyntaxStyle.fromStyles(), SyntaxStyle.fromTheme(), TextBuffer.create() 및 EditBuffer.create()는 마지막 인수로 소유자(owner)를 받습니다. OptimizedBuffer.create()는 owner 옵션으로 받습니다. context.renderer.nativeScene을 전달하세요. OpenTUI 0.5는 추가 인수를 무시하므로 플러그인은 이전 OpenCode 릴리스에서도 계속 실행됩니다.
  • @opencode/theme/tui의 generateSyntax()는 두 번째 인수로 소유자를 받습니다(generateSyntax(context.theme, context.renderer.nativeScene)). 이전 @opencode/theme 버전은 소유자 없이 스타일을 생성하므로 해당 패키지도 함께 업데이트하세요.
  • getLayoutNode()가 제거되었습니다. OpenTUI 0.6.5 이상에서는 getLayoutNode().getMaxWidth() 및 기타 스타일 게터를 동일한 이름의 렌더러블 메서드로 교체하세요. getComputedLayout() 및 기타 계산된 위치/크기 게터는 getLayout()으로, markDirty()는 invalidateIntrinsicSize()로 교체하세요. 계산된 padding, margin, border에는 대체 API가 없으며, getPadding(edge)는 해당 방향에 설정된 padding만 읽습니다. OpenTUI 0.6.6 이상에서 게터가 미설정(Unit.Undefined)으로 보고하는 스타일을 복원하려면 해당 속성에 undefined를 할당하세요.

모든 변경 사항은 OpenTUI 0.6.0 릴리스 노트 (opens in a new tab)에 나열되어 있습니다.

Solid 컴포넌트

라우트, 대화 상자 또는 슬롯이 렌더링하는 JSX 내부에서 현재 컨텍스트에 액세스하려면 usePlugin을 사용하세요.

import { usePlugin } from "@opencode/plugin/tui"
 
function Status() {
  const context = usePlugin()
  return <text fg={context.theme.text.base}>{context.app.version}</text>
}

Markdown

언어별로 펜스 코드 블록 렌더러를 등록할 수 있습니다. 반환된 함수를 호출하면 등록이 해제됩니다.

const unregister = context.markdown.registerCodeBlockRenderer("acme", (_token, render) => render.defaultRender())
return unregister

명령어 및 키맵

반응형(reactive) 키맵 레이어에 팔레트, 슬래시 및 키보드 명령어를 등록합니다.

context.keymap.layer(() => ({
  mode: "global",
  priority: 10,
  commands: [
    {
      id: "acme.status",
      title: "Show Acme status",
      group: "Acme",
      bind: "ctrl+g",
      palette: true,
      slash: { name: "acme", aliases: ["status"], arguments: true },
      enabled: () => true,
      suggested: true,
      run: async (input) => context.ui.toast.show({ message: input ?? "Ready" }),
    },
  ],
  bindings: ["acme.status"],
}))

setup(await 이후 포함) 또는 컴포넌트 내부에서 layer를 호출할 수 있습니다. 각 레이어는 다음 중 먼저 발생하는 시점에 제거됩니다.

  • 플러그인이 비활성화되거나, 다시 로드되거나, setup에 실패한 경우.
  • 레이어를 생성한 컴포넌트나 반응형 연산(예: 슬롯, 라우트, 대화 상자)이 해제(dispose)된 경우.

레이어 팩토리는 순수 함수여야 합니다. OpenCode는 초기 명령어 형태를 검증하기 위해 의존성 추적 없이 한 번 평가한 다음 반응형으로 평가합니다. ID가 없는 팔레트 명령어 같은 초기 형태 오류는 layer()에서 예외를 던집니다. 바인딩 파싱 오류는 OpenTUI가 처리합니다. 이후 반응형 업데이트 중 발생하는 오류는 Solid의 오류 처리를 따릅니다.

async setup(context) {
  const settings = await loadSettings()
  context.keymap.layer(() => ({
    mode: "global",
    commands: [{ id: "acme.sync", title: "Sync Acme", palette: true, run: () => sync(settings) }],
  }))
}

레이어는 단일 OpenTUI 렌더러블을 대상으로 지정할 수 있으며, 명령어에서 false를 반환하여 키보드 디스패치를 계속 진행하게 할 수 있습니다.

context.keymap.layer(() => ({
  target: () => panel,
  commands: [{ bind: "escape", run: (_input, event) => (event ? false : undefined) }],
}))

명령어를 디스패치하거나, 단축키와 명령어 상태를 검사하거나, 임시 입력 모드를 푸시할 수 있습니다.

context.keymap.dispatch("acme.status", "verbose")
const shortcuts = context.keymap.shortcuts("acme.status")
const commands = context.keymap.commands()
const pending = context.keymap.pending()
const active = context.keymap.active()
const currentMode = context.keymap.mode.current()
const popMode = context.keymap.mode.push("acme-search")
popMode()

스토리지

영구 스토리지는 재시작 후에도 JSON을 유지하며 여러 TUI 인스턴스 간에 동기화됩니다.

const [settings, updateSettings] = context.storage.store("settings", {
  initial: { compact: false },
})
await updateSettings((draft) => {
  draft.compact = true
})

메모리 스토리지는 플러그인 리로드 후에도 유지되지만 TUI가 종료되면 삭제됩니다.

const [state, updateState] = context.storage.memory("state", {
  initial: { count: 0 },
})
updateState((draft) => {
  draft.count++
})

대화 상자 및 토스트

알림(alert), 확인(confirm), 텍스트 입력(prompt) 및 선택(select)에 Promise 기반 대화 상자를 사용하세요.

await context.ui.dialog.alert({ title: "Acme", message: "Ready" })
const confirmed = await context.ui.dialog.confirm({
  title: "Continue?",
  message: "Run the Acme action?",
  label: { confirm: "Run", cancel: "Cancel" },
})
const name = await context.ui.dialog.prompt({ title: "Name", placeholder: "release" })
const mode = await context.ui.dialog.select({
  title: "Mode",
  current: "safe",
  options: [
    { title: "Safe", value: "safe", description: "Ask before changes" },
    { title: "Fast", value: "fast", disabled: false, category: "Advanced" },
  ],
})

선택 검색

매칭 및 결과 정렬을 직접 제어하려면 search를 전달하세요. 빈 쿼리를 포함한 모든 쿼리에 대해 실행되며 활성화된 옵션만 전달받습니다. 결과는 반환된 순서대로 표시되며 각 카테고리가 인라인으로 나타납니다.

const project = await context.ui.dialog.select({
  title: "Projects",
  options: [
    { title: "Alpha", value: "alpha", category: "Recent" },
    { title: "Beta", value: "beta", category: "Pinned" },
  ],
  search: (query, options) =>
    options
      .filter((option) => option.title.toLowerCase().includes(query.toLowerCase()))
      .toSorted((left, right) => right.title.localeCompare(left.title)),
})

선택 액션

액션은 푸터에 표시되며 키보드 바인딩, 클릭 또는 Tab 포커스 후 Enter로 실행됩니다. 기본적으로 선택된 값을 전달받으며 선택 항목이 없으면 사용할 수 없습니다. 선택 항목이 필요 없는 액션에는 selection: "none"을 사용하세요.

await context.ui.dialog.select({
  title: "Projects",
  options: [{ title: "Alpha", value: "alpha" }],
  actions: [
    { bind: "ctrl+o", title: "Inspect", onTrigger: (value) => context.ui.toast.show({ message: value }) },
    { bind: "ctrl+a", title: "Close", side: "right", selection: "none", onTrigger: () => context.ui.dialog.clear() },
  ],
})
  • 액션은 대화 상자를 닫거나 Promise를 확정(settle)하지 않습니다.
  • Enter를 누르거나 옵션을 클릭하면 선택된 값으로 resolve됩니다.
  • Escape, clear() 또는 다른 대화 상자를 표시하면 undefined로 resolve됩니다.
  • ctrl+n이나 ctrl+p는 바인딩하지 마세요. 대화 상자가 탐색용으로 예약하고 있으며 자체 바인딩이 우선합니다.

사용자 지정 JSX 대화 상자는 크기를 설정하고 스스로 닫을 수 있습니다.

context.ui.dialog.set({ size: "large", centered: true })
context.ui.dialog.show(
  () => (
    <box>
      <text>Acme</text>
    </box>
  ),
  () => console.log("closed"),
)
context.ui.dialog.clear()

토스트는 제목, 메시지, 변형(variant) 및 지속 시간(duration)을 지원합니다.

context.ui.toast.show({
  title: "Acme",
  message: "Saved",
  variant: "success",
  duration: 3000,
})

라우트 및 탭

JSX 라우트를 등록하고 현재 라우트를 검사하며 홈, 세션 또는 플러그인 페이지로 이동할 수 있습니다.

const unregister = context.ui.router.register({
  name: "dashboard",
  render: ({ data }) => <text>{String(data?.title ?? "Acme")}</text>,
})
const current = context.ui.router.current()
context.ui.router.navigate({ type: "plugin", name: "dashboard", data: { title: "Status" } })
context.ui.router.navigate({ type: "session", sessionID })
context.ui.router.navigate({ type: "home" })
return unregister

세션 탭이 활성화된 경우 탭을 나열, 열기, 포커스, 이동 및 닫기할 수 있습니다. open은 포커스를 변경하지 않으며, focus는 필요한 경우 탭을 엽니다.

if (context.ui.tabs.enabled()) {
  context.ui.tabs.open(backgroundSessionID)
  context.ui.tabs.focus(sessionID)
  const tabs = context.ui.tabs.list()
  context.ui.tabs.move(backgroundSessionID, tabs.length - 1)
  context.ui.tabs.close(sessionID)
  context.ui.tabs.close()
}

모델

프롬프트에서 선택된 모델을 읽고 변형(variant)을 변경할 수 있습니다. current()와 variant.list()는 Solid 연산 내에서 읽을 때 반응형으로 동작합니다. variant가 undefined이면 모델 기본값을 의미합니다.

const selected = context.ui.model.current()
const variants = context.ui.model.variant.list()
context.ui.model.variant.set("high")
context.ui.model.variant.set(undefined)

선택된 모델이 없거나 모델에 해당 변형이 없으면 variant.set은 false를 반환합니다. 예를 들어 모델 기본값을 건너뛰도록 내장 변형 순환을 대체하려면 명령어에 바인딩하세요.

context.keymap.layer(() => ({
  commands: [
    {
      id: "acme.variant.cycle",
      title: "Cycle variants",
      bind: "tab",
      run() {
        const variants = context.ui.model.variant.list()
        if (variants.length === 0) return
        const index = variants.indexOf(context.ui.model.current()?.variant ?? "")
        context.ui.model.variant.set(variants[(index + 1) % variants.length])
      },
    },
  ],
}))

슬롯

슬롯은 app, home.footer, home.footer.status, prompt.footer, prompt.footer.status, prompt.footer.file, session.composer.top, sidebar.content 또는 sidebar.footer 위치에 JSX를 삽입하거나 교체합니다.

return context.ui.slot({
  append: "sidebar.content",
  render: ({ sessionID }) => <text>{context.data.session.get(sessionID)?.title}</text>,
})

배치 방식에는 prepend, append, before, after 또는 replace를 사용합니다.

context.ui.slot({ prepend: "home.footer", render: () => <text>Before footer content</text> })
context.ui.slot({ append: "home.footer", render: () => <text>After footer content</text> })
context.ui.slot({ before: "home.footer", render: () => <text>Before footer slot</text> })
context.ui.slot({ after: "home.footer", render: () => <text>After footer slot</text> })
context.ui.slot({ replace: "home.footer", render: () => <text>New footer</text> })

내장 푸터 행을 교체하지 않고 콘텐츠를 추가하려면 home.footer.status를 사용하세요. 상태 기여 요소는 OpenCode의 상태 표시기 뒤이자 버전 앞에 표시됩니다.

context.ui.slot({ append: "home.footer.status", render: () => <text>SYNCED</text> })

세션 패널

session.panel에 기여 요소를 등록한 뒤 명령어에서 패널을 열 수 있습니다. 호스트가 크기 조정, 포커스 및 전체 화면 표시를 담당하고 플러그인은 내부 콘텐츠를 소유합니다. 선택된 이름은 모든 기여 요소에 panel.name으로 전달되며 각 기여 요소가 렌더링 여부를 결정합니다.

import { Show } from "solid-js"
 
context.ui.slot({
  append: "session.panel",
  render: (panel) => (
    <Show when={panel.name === "acme.review"}>
      <ReviewPanel panel={panel} />
    </Show>
  ),
})
 
context.ui.slot({
  append: "app",
  render: () => {
    context.keymap.layer(() => ({
      mode: "global",
      commands: [
        {
          id: "acme.review",
          title: "Open review",
          slash: { name: "review" },
          run: () => {
            context.ui.panel.open("acme.review")
          },
        },
      ],
    }))
    return null
  },
})
  • 세션 외부에서 열면 false를 반환합니다.
  • 일반 슬롯과 동일하므로 5가지 배치 방식과 기존 교체 우선순위 규칙이 모두 적용됩니다.
  • 독립적으로 선택 가능한 기여 요소들이 공존할 수 있도록 append를 사용하세요. replace는 여전히 슬롯 전체를 차지합니다.
  • 이름은 등록된 소유권이 아니라 공유 선택 값입니다. 충돌을 피하려면 acme.review처럼 플러그인 접두사가 붙은 이름을 사용하세요. 일치하는 렌더러가 없는 이름을 열면 슬롯이 비어 있게 됩니다.
  • 표시 방식(presentation)을 변경해도 마운트된 기여 요소는 유지됩니다. 패널을 닫으면 해제되며, 플러그인을 비활성화하면 일반 슬롯 정리를 통해 기여 요소가 제거됩니다.
  • 패널의 키보드 레이어와 입력 모드는 패널이 입력을 소유한 동안에만 활성화됩니다.

슬롯은 반응형 name, sessionID, width, presentation, focused 속성과 함께 focus, close, toggleFullscreen 액션을 전달받습니다. 호스트는 좁은 터미널에서 전체 화면을 유지하므로 측면 패널을 표시할 공간이 충분해질 때까지 toggleFullscreen은 효과가 없습니다.

import type { PanelInput } from "@opencode/plugin/tui/context"
import { usePlugin } from "@opencode/plugin/tui"
 
function ReviewPanel(props: { panel: PanelInput }) {
  const context = usePlugin()
  context.keymap.layer(() => ({
    commands: [
      {
        id: "acme.review.fullscreen",
        bind: "f",
        run: props.panel.toggleFullscreen,
      },
    ],
  }))
  return <text>Reviewing {props.panel.sessionID}</text>
}

처음부터 전체 화면 표시를 요청하거나, 활성 패널을 검사하거나, 다른 플러그인의 패널에 영향을 주지 않고 자신의 패널을 닫을 수 있습니다.

context.ui.panel.open("acme.review", { presentation: "fullscreen" })
const current = context.ui.panel.current()
context.ui.panel.close()

포맷팅

홈 디렉터리 축약을 포함해 화면 표시용으로 파일 시스템 경로를 포맷합니다.

const displayPath = context.ui.format.path(context.location?.directory ?? "/home/me/project")

게시 및 로드

./tui를 통해 TUI 플러그인을 노출하세요. 플러그인이 JSX를 렌더링하는 경우 OpenTUI peer 의존성을 추가하세요.

package.json
{
  "name": "opencode-acme-plugin",
  "type": "module",
  "exports": {
    ".": "./src/index.ts",
    "./tui": "./src/tui.tsx"
  },
  "dependencies": {
    "@opencode/plugin": "latest"
  },
  "peerDependencies": {
    "@opentui/core": ">=0.6.6",
    "@opentui/solid": ">=0.6.6",
    "solid-js": ">=1.9.0"
  }
}

자동 로드를 위해 서버 파트 또는 GUI 파트와 함께 ./tui를 export하세요.

src/index.ts
import { Plugin } from "@opencode/plugin"
 
export default Plugin.define({
  id: "acme.server",
  setup() {},
})

원격 서버에 대해서도 활성 상태를 유지하려면 TUI 전용 패키지를 cli.json에 설정하세요.

cli.json
{
  "plugins": ["opencode-acme-plugin"]
}