99// Override via opts / ICA_OC_PROVIDER + ICA_OC_MODEL.
1010
1111import { createOpencode , createOpencodeClient , createOpencodeServer } from '@opencode-ai/sdk'
12+ import type { AgentEvent } from './session.js'
1213import type { Session , RunHandlers , RunResult } from './session.js' // the shared session interface
1314
1415export interface OpencodeSessionOpts {
@@ -61,6 +62,28 @@ function fmtEvent(e: any, seen: Map<string, number>, asst: Set<string>): string
6162 return ''
6263}
6364
65+ // Normalize ONE opencode message part → AgentEvent for the UI event log (null = not rendered).
66+ // FORMAT CONTRACT — @opencode-ai/sdk 1.18. NOTE: opencode's /event SSE stopped delivering message.part.updated
67+ // since 1.14.42 (upstream bug anomalyco/opencode#27966), so we do NOT rely on the SSE for parts — we POLL
68+ // session.messages (see below) and normalize the parts here. Parts: {type:'text', id, text} and
69+ // {type:'tool', id, tool|name, state:{status, input, output}}. Stable part id → the UI updates a block in place.
70+ function normPart ( part : any ) : AgentEvent | null {
71+ if ( ! part ) return null
72+ if ( part . type === 'text' && typeof part . text === 'string' && part . text . trim ( ) ) {
73+ return { kind : 'message' , id : part . id , text : part . text }
74+ }
75+ if ( part . type === 'tool' ) {
76+ const name = part . tool || part . name || 'tool'
77+ const st = part . state || { }
78+ const input = st . input || part . input || { }
79+ const d = input . command || input . filePath || input . path || ( input . sql ? String ( input . sql ) . replace ( / \s + / g, ' ' ) . slice ( 0 , 200 ) : '' )
80+ const output = typeof st . output === 'string' ? st . output : ( st . output ? JSON . stringify ( st . output ) . slice ( 0 , 4000 ) : '' )
81+ const status = st . status
82+ return { kind : 'command' , id : part . id , command : `${ name } ${ d ? ' ' + d : '' } ` . trim ( ) , output, status, done : status === 'completed' || status === 'error' }
83+ }
84+ return null
85+ }
86+
6487export function createOpencodeSession ( opts : OpencodeSessionOpts ) : Session {
6588 const providerID = opts . provider ?? process . env . ICA_OC_PROVIDER ?? 'opencode-go'
6689 const modelID = opts . model ?? process . env . ICA_OC_MODEL ?? 'glm-5.2'
@@ -71,6 +94,8 @@ export function createOpencodeSession(opts: OpencodeSessionOpts): Session {
7194 let sse : AbortController | null = null // aborts OUR event subscription on stop (so closing a server doesn't ECONNRESET-reject)
7295 let sessionId = ''
7396 let buf = ''
97+ const eventLog : AgentEvent [ ] = [ ] // structured events (the 'events' view), fed by POLLING (SSE is broken)
98+ const polled = new Map < string , string > ( ) // part id → last signature, so we emit only on change
7499 let running = false
75100 let activeHandler : RunHandlers | undefined
76101 const queue : { prompt : string ; h ?: RunHandlers ; resolve : ( r : RunResult ) => void } [ ] = [ ]
@@ -120,6 +145,29 @@ export function createOpencodeSession(opts: OpencodeSessionOpts): Session {
120145 } ) ( ) . catch ( ( ) => { } )
121146 }
122147
148+ // Emit one normalized event: update the block with the same id, else append; skip if unchanged since last poll.
149+ function emit ( ne : AgentEvent , h ?: RunHandlers ) {
150+ const sig = `${ ne . text ?. length ?? 0 } :${ ne . output ?. length ?? 0 } :${ ne . status ?? '' } :${ ne . done ? 1 : 0 } `
151+ if ( ne . id && polled . get ( ne . id ) === sig ) return
152+ if ( ne . id ) polled . set ( ne . id , sig )
153+ if ( ne . id ) { const i = eventLog . findIndex ( x => x . id === ne . id ) ; if ( i >= 0 ) eventLog [ i ] = ne ; else eventLog . push ( ne ) }
154+ else eventLog . push ( ne )
155+ if ( eventLog . length > 600 ) eventLog . shift ( )
156+ h ?. onEvent ?.( ne )
157+ }
158+ // Poll the session's messages → normalize the assistant parts → emit changed events. This is the live event
159+ // source (opencode's SSE part stream is broken since 1.14.42, #27966), polled every ~1s during a turn.
160+ async function pollMessages ( h ?: RunHandlers ) {
161+ try {
162+ const res : any = await client . session . messages ( { path : { id : sessionId } , query : { directory : opts . cwd } } )
163+ for ( const m of ( res ?. data ?? res ?? [ ] ) ) {
164+ const info = m . info ?? m
165+ if ( info ?. role !== 'assistant' ) continue
166+ for ( const part of ( m . parts ?? info . parts ?? [ ] ) ) { const ne = normPart ( part ) ; if ( ne ) emit ( ne , h ) }
167+ }
168+ } catch { /* transient — next poll retries */ }
169+ }
170+
123171 async function pump ( ) {
124172 if ( running || ! queue . length ) return
125173 running = true
@@ -128,6 +176,7 @@ export function createOpencodeSession(opts: OpencodeSessionOpts): Session {
128176 activeHandler = h
129177 const t0 = Date . now ( )
130178 let answer = ''
179+ const poll = setInterval ( ( ) => { void pollMessages ( h ) } , 1000 ) // live events via polling (SSE parts broken)
131180 try {
132181 const res = await client . session . prompt ( { // resolves when the turn is DONE (exact completion)
133182 path : { id : sessionId } ,
@@ -136,6 +185,7 @@ export function createOpencodeSession(opts: OpencodeSessionOpts): Session {
136185 } )
137186 answer = partsText ( res ?. data ?. parts ?? res ?. parts ?? [ ] )
138187 } catch ( e : any ) { answer = `opencode error: ${ e ?. message ?? e } ` }
188+ finally { clearInterval ( poll ) ; await pollMessages ( h ) } // one final poll to catch the last state
139189 activeHandler = undefined
140190 running = false
141191 resolve ( { lastLines : answer , ms : Date . now ( ) - t0 } )
@@ -149,6 +199,7 @@ export function createOpencodeSession(opts: OpencodeSessionOpts): Session {
149199 return { lastLines : '(opencode summarized session context)' , ms : 0 }
150200 } ,
151201 buffer : ( ) => buf ,
202+ events : ( ) => eventLog ,
152203 busy : ( ) => running ,
153204 // Clean up OUR session on the server either way; stop the SERVER only if we spawned it.
154205 // If we connected to a shared/standalone server, leave it running for everyone else.
0 commit comments