Effect 클라이언트
타입이 지정된 Effect와 Stream을 반환하는 @opencode/client/effect를 사용해 Effect에서 OpenCode HTTP API를 호출합니다.
@opencode/client/effect는 OpenCode HTTP API용 Effect 네이티브 클라이언트입니다. 타입이 지정된 Effect와 Stream을 반환하며 응답을 OpenCode 스키마 값으로 디코딩합니다.
bun add @opencode/client [email protected]클라이언트 생성
서버 URL로 클라이언트를 생성한 다음 API 리소스별로 그룹화된 메서드를 호출합니다.
import { AbsolutePath, Location, OpenCode } from "@opencode/client/effect"
import { Effect } from "effect"
import { FetchHttpClient } from "effect/http"
const program = Effect.gen(function* () {
const client = yield* OpenCode.make({ baseUrl: "http://localhost:4096" })
const session = yield* client.session.create({
location: Location.Ref.make({ directory: AbsolutePath.make("/workspace") }),
})
yield* client.session.prompt({
sessionID: session.id,
text: "Review the current changes",
})
return session
})
const session = await Effect.runPromise(program.pipe(Effect.provide(FetchHttpClient.layer)))헤더 및 요청
제공되는 HttpClient에 기본 헤더를 설정하세요. 네이티브 작업은 취소를 위해 일반 Effect 인터럽트(interruption)를 사용합니다. RPC 메서드는 호출별 location, 헤더 및 시그널 옵션을 추가로 받습니다.
{/* prettier-ignore */}
import { HttpClient, HttpClientRequest } from "effect/http"
const httpClient = yield* HttpClient.HttpClient
const client = yield* OpenCode.make({ baseUrl: "https://opencode.example.com" }).pipe(
Effect.provideService(
HttpClient.HttpClient,
HttpClient.mapRequest(httpClient, (request) =>
HttpClientRequest.setHeaders(request, { authorization: `Bearer ${process.env.OPENCODE_TOKEN}` }),
),
),
)
const sessions = yield* client.session.list()이벤트 스트리밍
event.subscribe() 및 experimental.session.log() 같은 스트리밍 작업은 Effect Stream을 반환합니다.
{/* prettier-ignore */}
import { Effect, Stream } from "effect"
yield* client.event
.subscribe()
.pipe(Stream.runForEach((event) => Effect.logInfo("OpenCode event", { type: event.type })))네이티브 및 RPC 이벤트 Stream은 클라이언트당 하나의 지연(lazy) 연결을 공유합니다. Stream을 생성할 때는 연결되지 않으며 소비할 때 연결됩니다. 하나의 소비자를 중지해도 다른 소비자는 계속 실행되며, 마지막 소비자가 떠나면 소스가 닫힙니다. 소스 EOF 또는 오류가 발생하면 자동 재시도나 재전송 없이 현재 구독이 종료됩니다. 늦게 합류한 네이티브 소비자는 실시간 이벤트 전에 현재 연결 마커를 수신합니다.
플러그인 RPC
Promise 클라이언트 및 서버 플러그인과 동일한 공유 계약을 사용합니다.
{/* prettier-ignore */}
import { Acme } from "opencode-acme-plugin/rpc"
const acme = client.rpc(Acme)
const result = yield* acme.search({ query: "hello" }, { location: { directory: "/workspace" } })
yield* acme.events
.subscribe("updated")
.pipe(
Stream.runForEach((event) =>
Effect.logInfo("Plugin event", { type: event.type, location: event.location, text: event.data.text }),
),
)메서드 인수와 결과는 계약에서 추론됩니다. 선택적 두 번째 인수는 location, signal, headers를 담으며, location을 생략하면 일반 요청 기본값이 사용됩니다. 호출은 이를 소비하는 Effect와 함께 인터럽트됩니다. 메서드 오류 맵은 Effect 오류 채널에 추론되며 선언된 오류는 해당 데이터 스키마를 통해 디코딩됩니다. 타입이 지정된 서브클라이언트는 일반 HTTP RPC 오류 래퍼를 제거하며, 예약된 rpc.* 타입은 프레임워크 실패를 식별합니다.
RPC 이벤트는 콜백 스타일의 on 리스너가 아니라 타입이 지정된 Stream입니다. 모든 위치에서 해당 RPC의 이벤트를 수신하며, 각 이벤트는 필수 location과 rpc.acme.updated 같은 일반 접두사 타입을 가집니다. 이는 자체 위치에 고정되는 서버 플러그인 핸들과 다릅니다. 정의, 스키마, 등록 및 실시간 구독 의미 체계에 대해서는 Effect 플러그인 RPC를 참고하세요.
로컬 백그라운드 서비스
Node 전용 @opencode/client/effect/service 진입점은 로컬 백그라운드 서비스를 Effect로 검색, 시작, 인증 및 중지합니다.
bun add @effect/[email protected]보장(ensured)된 서비스에 대한 인증된 클라이언트를 생성합니다.
import { NodeFileSystem } from "@effect/platform-node"
import { OpenCode } from "@opencode/client/effect"
import { Service } from "@opencode/client/effect/service"
import { Effect } from "effect"
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"
const program = Effect.gen(function* () {
const endpoint = yield* Service.ensure()
const httpClient = yield* HttpClient.HttpClient
const client = yield* OpenCode.make({ baseUrl: endpoint.url }).pipe(
Effect.provideService(
HttpClient.HttpClient,
HttpClient.mapRequest(httpClient, (request) =>
HttpClientRequest.setHeaders(request, Service.headers(endpoint) ?? {}),
),
),
)
return yield* client.server.info()
})
const health = await Effect.runPromise(
program.pipe(Effect.provide(FetchHttpClient.layer), Effect.provide(NodeFileSystem.layer)),
)서비스를 시작하지 않고 검색하거나 정확히 등록된 서비스를 중지할 수 있습니다.
{/* prettier-ignore */}
const endpoint = yield* Service.discover()
yield* Service.stop()