Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

server.ts

270 lines9.5 KB

1import { createOpencode, createOpencodeClient } from '@opencode-ai/sdk'
2import type { Config, Event, OpencodeClient, Part } from '@opencode-ai/sdk'
3import type {
4 OpencodeAssistantMessage,
5 OpencodeEvent,
6} from '../stream/sdk-types'
7import type {
8 OpencodePermissionRequest,
9 OpencodePermissionResponse,
10} from './permissions'
11​
12/** A live OpenCode session backed by an `opencode serve` HTTP server. */
13export interface OpencodeSessionHandle {
14 sessionId: string
15 /** Whether an existing session was actually resumed. */
16 resumed: boolean
17 /**
18 * Run one prompt turn. Resolves with the final assistant message (finish
19 * reason, token usage, error) and its concatenated text once the harness
20 * goes idle. Streaming deltas arrive via `onEvent` while this is pending.
21 */
22 prompt: (
23 text: string,
24 ) => Promise<{ message: OpencodeAssistantMessage; text: string }>
25 /** Ask the harness to abort the in-flight prompt turn. */
26 abort: () => Promise<void>
27 /** Tear down the event subscription and (if owned) the server. */
28 dispose: () => Promise<void>
30​
31export interface StartOpencodeSessionOptions {
32 /** Connect to an already-running server instead of spawning one. */
33 baseUrl?: string
34 /**
35 * Headers attached to every request to the opencode server — used to
36 * authenticate a token-gated preview channel (e.g. Daytona). Without them a
37 * gated preview proxy rejects the requests (404 "Not found.").
38 */
39 headers?: Record<string, string>
40 /** Hostname for the spawned server. Defaults to the SDK default. */
41 hostname?: string
42 /** Port for the spawned server. Defaults to the SDK default. */
43 port?: number
44 /**
45 * Directory the opencode HTTP API scopes the session to. Omit to use the
46 * server's own launch cwd (the common case): the server is spawned with the
47 * correct working dir per-provider, so passing a directory here is only needed
48 * to override it. Passing a VIRTUAL sandbox path (e.g. `/workspace`) is wrong
49 * for host-running providers (local-process), where that path doesn't exist —
50 * the API then stalls on it. Leave undefined and rely on the server cwd.
51 */
52 directory?: string
53 /** Provider id (the part before `/` in the model id). */
54 providerID: string
55 /** Model id (the part after `/` in the model id). */
56 modelID: string
57 /** Extra OpenCode config merged with the adapter's mcp/permission config. */
58 config?: Config
59 /** Baseline permission policy applied to the spawned server. */
60 permission?: Config['permission']
61 /** MCP servers (e.g. the TanStack tool bridge) for the session. */
62 mcpServers?: Array<{ name: string; url: string }>
63 /** Session id to resume; falls back to a fresh session when not found. */
64 resumeSessionId?: string
65 onEvent: (event: OpencodeEvent) => void
66 onPermissionRequest: (
67 request: OpencodePermissionRequest,
68 ) => Promise<OpencodePermissionResponse> | OpencodePermissionResponse
69 /** Called when the event subscription fails mid-turn. */
70 onError?: (error: unknown) => void
72​
73/** Locate the session id an OpenCode event belongs to, when it carries one. */
74function sessionIdOf(event: Event): string | undefined {
75 const props = event.properties as { sessionID?: string } | undefined
76 if (props?.sessionID !== undefined) return props.sessionID
77 if (event.type === 'message.part.updated') {
78 return event.properties.part.sessionID
79 }
80 if (event.type === 'message.updated') {
81 return event.properties.info.sessionID
82 }
83 if (event.type === 'permission.updated') {
84 return event.properties.sessionID
85 }
86 return undefined
88​
89function buildConfig(options: StartOpencodeSessionOptions): Config {
90 const mcp: NonNullable<Config['mcp']> = { ...options.config?.mcp }
91 for (const server of options.mcpServers ?? []) {
92 mcp[server.name] = { type: 'remote', url: server.url, enabled: true }
93 }
94 return {
95 ...options.config,
96 ...(Object.keys(mcp).length > 0 && { mcp }),
97 ...(options.permission !== undefined && { permission: options.permission }),
98 }
100​
101/**
102 * Boot (or attach to) an OpenCode HTTP server, resolve a session, and wire its
103 * event subscription + permission replies.
104 *
105 * This module is the only place that touches `@opencode-ai/sdk`; the rest of
106 * the package works with the structural types in `sdk-types.ts`.
107 *
108 * Resume semantics: when `resumeSessionId` is set and the server still knows
109 * the session (same machine, same data dir), it is reused. Otherwise a fresh
110 * session is created and `resumed: false` tells the adapter to send the
111 * flattened transcript.
112 */
113export async function startOpencodeSession(
114 options: StartOpencodeSessionOptions,
115): Promise<OpencodeSessionHandle> {
116 const { directory } = options
117 // Spread into a `query` object only when set; omitting lets opencode use the
118 // server's launch cwd (correct for every provider — see `directory` docs).
119 const dirQuery = directory !== undefined ? { directory } : {}
120​
121 let client: OpencodeClient
122 let ownedServer: { close: () => void } | undefined
123​
124 if (options.baseUrl !== undefined) {
125 client = createOpencodeClient({
126 baseUrl: options.baseUrl,
127 ...(options.headers !== undefined && { headers: options.headers }),
128 ...(directory !== undefined && { directory }),
129 })
130 } else {
131 const config = buildConfig(options)
132 const result = await createOpencode({
133 ...(options.hostname !== undefined && { hostname: options.hostname }),
134 ...(options.port !== undefined && { port: options.port }),
135 ...(Object.keys(config).length > 0 && { config }),
136 })
137 client = result.client
138 ownedServer = result.server
139 }
140​
141 // Mutated from several closures (the subscription loop, dispose, teardown);
142 // a holder object keeps reads typed as `boolean` rather than being
143 // flow-narrowed to a literal across those boundaries.
144 const lifecycle = { disposed: false }
145​
146 const teardown = async (): Promise<void> => {
147 if (lifecycle.disposed) return
148 lifecycle.disposed = true
149 ownedServer?.close()
150 await Promise.resolve()
151 }
152​
153 try {
154 // Resolve the session before subscribing so the event filter has an id.
155 let sessionId: string | undefined
156 let resumed = false
157 if (options.resumeSessionId !== undefined) {
158 const existing = await client.session.get({
159 path: { id: options.resumeSessionId },
160 query: dirQuery,
161 })
162 if (existing.data) {
163 sessionId = options.resumeSessionId
164 resumed = true
165 }
166 }
167 if (sessionId === undefined) {
168 const created = await client.session.create({
169 query: dirQuery,
170 body: {},
171 throwOnError: true,
172 })
173 sessionId = created.data.id
174 }
175 const resolvedSessionId = sessionId
176​
177 const handlePermission = async (
178 permission: Extract<Event, { type: 'permission.updated' }>['properties'],
179 ): Promise<void> => {
180 try {
181 const response = await options.onPermissionRequest({
182 id: permission.id,
183 sessionID: permission.sessionID,
184 type: permission.type,
185 title: permission.title,
186 ...(permission.callID !== undefined && { callID: permission.callID }),
187 })
188 await client.postSessionIdPermissionsPermissionId({
189 path: { id: permission.sessionID, permissionID: permission.id },
190 query: dirQuery,
191 body: { response },
192 throwOnError: true,
193 })
194 } catch (error) {
195 if (!lifecycle.disposed) options.onError?.(error)
196 }
197 }
198​
199 const subscription = await client.event.subscribe()
200 const stream = subscription.stream
201​
202 void (async () => {
203 try {
204 for await (const event of stream) {
205 if (lifecycle.disposed) break
206 const sid = sessionIdOf(event)
207 if (sid !== undefined && sid !== resolvedSessionId) continue
208 if (event.type === 'permission.updated') {
209 void handlePermission(event.properties)
210 continue
211 }
212 // The SDK event union is a structural superset of the subset the
213 // translator consumes; unknown event types match no translator
214 // branch and are ignored.
215 options.onEvent(event as OpencodeEvent)
216 }
217 } catch (error) {
218 if (!lifecycle.disposed) options.onError?.(error)
219 }
220 })()
221​
222 return {
223 sessionId: resolvedSessionId,
224 resumed,
225 prompt: async (text: string) => {
226 const result = await client.session.prompt({
227 path: { id: resolvedSessionId },
228 query: dirQuery,
229 body: {
230 model: { providerID: options.providerID, modelID: options.modelID },
231 parts: [{ type: 'text', text }],
232 },
233 throwOnError: true,
234 })
235 const data = result.data
236 const message = data.info as OpencodeAssistantMessage
237 const responseText = data.parts
238 .filter(
239 (part): part is Extract<Part, { type: 'text' }> =>
240 part.type === 'text',
241 )
242 .map((part) => part.text)
243 .join('')
244 return { message, text: responseText }
245 },
246 abort: async () => {
247 try {
248 await client.session.abort({
249 path: { id: resolvedSessionId },
250 query: dirQuery,
251 })
252 } catch {
253 // Best-effort: the turn may already be finishing.
254 }
255 },
256 dispose: async () => {
257 lifecycle.disposed = true
258 try {
259 await stream.return(undefined)
260 } catch {
261 // Ignore: stream may already be closed.
262 }
263 ownedServer?.close()
264 },
265 }
266 } catch (error) {
267 await teardown()
268 throw error
269 }