-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathopencode-process.ts
More file actions
1595 lines (1477 loc) · 63.9 KB
/
Copy pathopencode-process.ts
File metadata and controls
1595 lines (1477 loc) · 63.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Manages an OpenCode server session via HTTP REST + SSE.
*
* OpenCode (github.com/anomalyco/opencode) uses a client/server architecture:
* - `opencode serve` runs a long-lived HTTP server
* - Sessions are created/managed via REST API
* - Real-time events stream via SSE (Server-Sent Events)
*
* This class wraps that model behind the same CodingProcess interface that
* ClaudeProcess implements, so SessionManager works identically for both.
*
* Key differences from ClaudeProcess:
* - No child process per session — one shared OpenCode server
* - Messages sent via HTTP POST, not stdin
* - Events received via SSE, not stdout NDJSON
* - Permissions handled via POST /permission/:id/reply, not control_response on stdin
*/
import { EventEmitter } from 'events'
import { spawn, type ChildProcess } from 'child_process'
import { randomUUID } from 'crypto'
import { readFileSync, existsSync, statSync } from 'fs'
import { extname } from 'path'
import type { ClaudeProcessEvents } from './claude-process.js'
import { OPENCODE_CAPABILITIES, type CodingProcess, type CodingProvider, type ProviderCapabilities } from './coding-process.js'
import type { PermissionMode, TaskItem } from './types.js'
import { summarizeToolInput } from './tool-labels.js'
// ---------------------------------------------------------------------------
// OpenCode SSE event types (subset — only what we need to map)
// ---------------------------------------------------------------------------
/** A part within an OpenCode message (text, reasoning, tool, step markers). */
interface OpenCodeMessagePart {
type: 'text' | 'reasoning' | 'tool' | 'step-start' | 'step-finish'
/** Text/reasoning content (field name is 'text', not 'content'). */
text?: string
/** Tool name (only for type='tool'). */
tool?: string
/** Tool state — an object, not a string. Contains status, input, output, time, etc. */
state?: {
status: 'pending' | 'running' | 'completed' | 'error'
input?: Record<string, unknown>
output?: string
error?: string
time?: { start?: number; end?: number }
metadata?: Record<string, unknown>
title?: string
}
time?: { start?: number; end?: number }
metadata?: Record<string, unknown>
}
/** Shape of an SSE event from OpenCode's GET /event endpoint. */
interface OpenCodeSSEEvent {
type: string
properties: Record<string, unknown>
}
// ---------------------------------------------------------------------------
// Codekin context + permission mapping
// ---------------------------------------------------------------------------
/**
* Codekin environment context appended to OpenCode's agent system prompt via
* the `system` field on each prompt request. OpenCode APPENDS this to its
* tuned per-model prompt (verified against OpenCode 1.15) — unlike
* `agent.*.prompt` config which would REPLACE it. Mirrors the
* `--append-system-prompt` text used for the Claude path (claude-process.ts).
*/
export const OPENCODE_SYSTEM_CONTEXT = [
'You are running inside a web-based terminal (Codekin).',
'Tool permissions are managed by the system through an approval UI.',
'Do not tell the user to click approve or grant permission. Just proceed with your work.',
'If a tool call fails, read the error message carefully. Common causes: wrong file path, missing dependency, syntax error, or network issue.',
].join(' ')
/** One rule in OpenCode's permission ruleset (last match wins, wildcards on both fields). */
interface OpenCodePermissionRule {
permission: string
pattern: string
action: 'allow' | 'deny' | 'ask'
}
/**
* Map Codekin's PermissionMode to an OpenCode permission ruleset, applied at
* session creation (and via PATCH on resume). Without this, bypass-mode
* sessions still hit server-side `ask` states (external_directory, doom_loop)
* that must round-trip through the UI even though the user opted out.
* Returns undefined for modes where OpenCode's defaults are appropriate.
*/
export function permissionRulesetFor(mode?: PermissionMode): OpenCodePermissionRule[] | undefined {
switch (mode) {
case 'bypassPermissions':
case 'dangerouslySkipPermissions':
return [{ permission: '*', pattern: '*', action: 'allow' }]
case 'acceptEdits':
return [{ permission: 'edit', pattern: '*', action: 'allow' }]
default:
// 'default' and 'plan' use OpenCode's defaults; plan-mode safety comes
// from selecting the read-only `plan` agent on each prompt.
return undefined
}
}
/** An OpenCode command (slash command / skill / MCP prompt) from GET /command. */
export interface OpenCodeCommandInfo {
name: string
description?: string
agent?: string
model?: string
source?: 'command' | 'mcp' | 'skill'
template?: string
hints?: string[]
}
// ---------------------------------------------------------------------------
// OpenCode server manager (singleton — one server for all sessions)
// ---------------------------------------------------------------------------
interface OpenCodeServerState {
process: ChildProcess | null
port: number
password: string
ready: boolean
startPromise: Promise<void> | null
}
const serverState: OpenCodeServerState = {
process: null,
port: 0,
password: '',
ready: false,
startPromise: null,
}
/**
* Ensure the OpenCode server is running. Starts it if not already running.
* Returns the base URL for API calls.
*/
async function ensureOpenCodeServer(workingDir: string): Promise<string> {
if (serverState.ready && serverState.process && !serverState.process.killed) {
return `http://localhost:${serverState.port}`
}
if (serverState.startPromise) {
await serverState.startPromise
return `http://localhost:${serverState.port}`
}
serverState.startPromise = startOpenCodeServer(workingDir)
try {
await serverState.startPromise
} finally {
serverState.startPromise = null
}
return `http://localhost:${serverState.port}`
}
async function startOpenCodeServer(workingDir: string): Promise<void> {
// Pick a port in the ephemeral range
serverState.port = 14096 + Math.floor(Math.random() * 1000)
serverState.password = randomUUID()
// Strip API keys and GIT_* vars (except GIT_EDITOR) — same filtering as
// claude-process.ts. GIT_INDEX_FILE=.git/index breaks worktrees where
// .git is a file, and stale API keys override OpenCode's own auth.
const API_KEY_VARS = new Set(['ANTHROPIC_API_KEY', 'CLAUDE_CODE_API_KEY', 'AUTH_TOKEN', 'AUTH_TOKEN_FILE'])
const env: Record<string, string> = {
...Object.fromEntries(
Object.entries(process.env).filter(
(entry): entry is [string, string] =>
entry[1] != null &&
!API_KEY_VARS.has(entry[0]) &&
(!entry[0].startsWith('GIT_') || entry[0] === 'GIT_EDITOR')
)
),
OPENCODE_SERVER_PASSWORD: serverState.password,
}
const proc = spawn('opencode', ['serve', '--port', String(serverState.port)], {
cwd: workingDir,
stdio: 'ignore', // prevents buffer deadlock — pipes were never drained
env,
})
serverState.process = proc
proc.on('close', () => {
serverState.ready = false
serverState.process = null
})
// Wait for server to become ready (poll health endpoint)
const baseUrl = `http://localhost:${serverState.port}`
const maxAttempts = 30
for (let i = 0; i < maxAttempts; i++) {
await new Promise(r => setTimeout(r, 1000))
try {
const res = await fetch(`${baseUrl}/health`, {
headers: authHeaders(),
signal: AbortSignal.timeout(2000),
})
if (res.ok) {
serverState.ready = true
console.log(`[opencode-server] Ready on port ${serverState.port}`)
// One-shot version check — warns when the server is older than the
// version this integration was built against. Non-fatal.
void checkServerVersion(baseUrl)
return
}
} catch {
// Server not ready yet
}
}
// Kill orphaned process that never became healthy
if (serverState.process) {
serverState.process.kill('SIGTERM')
serverState.process = null
}
throw new Error(`OpenCode server failed to start within ${maxAttempts}s`)
}
/** Minimum OpenCode version this integration is tested against. */
export const MIN_TESTED_OPENCODE_VERSION = '1.15.0'
/** Returns true when version `a` is older than version `b` (semver-ish numeric compare). */
export function isVersionOlder(a: string, b: string): boolean {
const pa = a.split('.').map(Number)
const pb = b.split('.').map(Number)
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
const x = pa[i] ?? 0
const y = pb[i] ?? 0
if (Number.isNaN(x) || Number.isNaN(y)) return false
if (x !== y) return x < y
}
return false
}
/**
* Query the server's version (GET /global/health) and warn when it's older
* than the version this integration was built against. Older servers may
* lack endpoints we rely on (summarize, abort, permission replies).
*/
async function checkServerVersion(baseUrl: string): Promise<void> {
try {
const res = await fetch(`${baseUrl}/global/health`, {
headers: authHeaders(),
signal: AbortSignal.timeout(5000),
})
if (!res.ok) return
const data = await res.json() as { version?: string }
if (typeof data.version !== 'string') return
if (isVersionOlder(data.version, MIN_TESTED_OPENCODE_VERSION)) {
console.warn(
`[opencode-server] Server version ${data.version} is older than the tested version ${MIN_TESTED_OPENCODE_VERSION} — ` +
'some features (compact, abort, native permissions) may not work. Consider upgrading OpenCode.'
)
} else {
console.log(`[opencode-server] Version ${data.version}`)
}
} catch {
// Older servers may not expose /global/health — nothing to report.
}
}
/** Build auth headers for OpenCode API calls. */
function authHeaders(): Record<string, string> {
if (!serverState.password) return {}
const encoded = Buffer.from(`opencode:${serverState.password}`).toString('base64')
return { Authorization: `Basic ${encoded}` }
}
/** OpenCode model info returned from /config/providers. */
export interface OpenCodeModelInfo {
id: string
name: string
providerID: string
providerName: string
}
/**
* Fetch the list of configured models from the running OpenCode server.
* Returns an empty array if the server is not running.
*/
export async function fetchOpenCodeModels(workingDir: string): Promise<{
models: OpenCodeModelInfo[]
defaults: Record<string, string>
}> {
try {
const baseUrl = await ensureOpenCodeServer(workingDir)
const res = await fetch(`${baseUrl}/config/providers`, {
headers: {
...authHeaders(),
'x-opencode-directory': workingDir,
},
signal: AbortSignal.timeout(15000),
})
if (!res.ok) return { models: [], defaults: {} }
const data = await res.json() as {
providers: Array<{
id: string
name: string
models: Record<string, { id: string; name: string }>
}>
default?: Record<string, string>
}
const models: OpenCodeModelInfo[] = []
for (const p of data.providers) {
for (const m of Object.values(p.models)) {
models.push({ id: m.id, name: m.name, providerID: p.id, providerName: p.name })
}
}
return { models, defaults: data.default ?? {} }
} catch {
return { models: [], defaults: {} }
}
}
/**
* Fetch the list of commands (slash commands, skills, MCP prompts) from the
* running OpenCode server. Returns an empty array if the server is not running.
*/
export async function fetchOpenCodeCommands(workingDir: string): Promise<OpenCodeCommandInfo[]> {
try {
const baseUrl = await ensureOpenCodeServer(workingDir)
const res = await fetch(`${baseUrl}/command`, {
headers: {
...authHeaders(),
'x-opencode-directory': workingDir,
},
signal: AbortSignal.timeout(15000),
})
if (!res.ok) return []
const data = await res.json() as OpenCodeCommandInfo[]
return Array.isArray(data) ? data : []
} catch {
return []
}
}
/** Stop the shared OpenCode server. */
export function stopOpenCodeServer(): void {
if (serverState.process) {
serverState.process.kill('SIGTERM')
serverState.process = null
serverState.ready = false
}
}
// ---------------------------------------------------------------------------
// Options
// ---------------------------------------------------------------------------
export interface OpenCodeProcessOptions {
/** Absolute path to the project directory. */
workingDir: string
/** Codekin session ID (used for internal tracking). */
sessionId?: string
/** OpenCode's own session ID (used for resume — returned by getSessionId()). */
opencodeSessionId?: string
/** Model in provider/model format (e.g. 'anthropic/claude-sonnet-4'). */
model?: string
/** Additional environment variables (CODEKIN_SESSION_ID, etc.). */
extraEnv?: Record<string, string>
/** Permission mode — mapped to OpenCode's permission config. */
permissionMode?: PermissionMode
/**
* Recent assistant output already shown to the user (concatenated text from
* the session's output history). Used on resume to avoid re-emitting an
* assistant message that was already displayed when hydrating missed history.
*/
recentOutputText?: string
}
// ---------------------------------------------------------------------------
// OpenCodeProcess
// ---------------------------------------------------------------------------
/** How often the turn watchdog checks for a stalled turn. */
const TURN_WATCHDOG_INTERVAL_MS = 30_000
/** How long without any session SSE event before we poll the server to resync. */
const TURN_STALL_THRESHOLD_MS = 60_000
export class OpenCodeProcess extends EventEmitter<ClaudeProcessEvents> implements CodingProcess {
readonly provider: CodingProvider = 'opencode'
readonly capabilities: ProviderCapabilities = OPENCODE_CAPABILITIES
private sessionId: string
private opencodeSessionId: string | null = null
private workingDir: string
private model?: string
private alive = false
private abortController: AbortController | null = null
private startupTimer: ReturnType<typeof setTimeout> | null = null
private permissionMode?: PermissionMode
/** OpenCode commands available on the server, keyed by name (for /name routing). */
private commands = new Map<string, OpenCodeCommandInfo>()
private tasks = new Map<string, TaskItem>()
private turnComplete = false
/** True while a prompt/command turn is running server-side (set on send, cleared on completion). */
private turnInFlight = false
/** OpenCode child sessions spawned by this session's subagents (task tool). */
private childSessionIds = new Set<string>()
/** Latest token/cost usage per assistant message ID (message.updated fires repeatedly). */
private usageByMessage = new Map<string, { input: number; output: number; cost: number }>()
/** Last emitted usage totals, serialized — suppresses duplicate usage events. */
private lastEmittedUsage = ''
/** Messages received while a turn was in flight — sent when the turn completes. */
private pendingMessages: string[] = []
/** Recent already-displayed assistant text (from output history) for resume hydration dedup. */
private recentOutputText = ''
private taskSeq = 0
/**
* Watchdog that detects turns stalled by a missed completion event.
* The turn-completion latch (turnComplete) is only released by SSE events
* (session.idle / message.completed / session.status). If the SSE stream
* drops and the completion event is lost, the turn would hang forever —
* the watchdog polls the server's message history to recover.
*/
private turnWatchdog: ReturnType<typeof setInterval> | null = null
/** Timestamp of the last SSE event explicitly scoped to this session. */
private lastSessionEventTime = 0
/** Whether we've received streaming delta events this turn (to avoid double-emitting text). */
private receivedDeltas = false
/** Whether we've already emitted text via message.part.updated (to avoid re-emitting from message.updated). */
private emittedPartText = false
/** Last user input text — used to detect and strip user echo from assistant deltas. */
private lastUserInput = ''
/** Buffer for initial text deltas — held until we can check for user echo prefix. */
private deltaBuffer = ''
/** Whether the delta buffer has been flushed (user echo check complete). */
private deltaBufferFlushed = false
/** Accumulated reasoning delta text for emitting thinking summaries during streaming. */
private reasoningBuffer = ''
/** Whether we've already emitted a thinking summary from reasoning deltas. */
private emittedReasoningSummary = false
/**
* Whether text deltas currently belong to a reasoning part rather than the
* actual response. Some providers (e.g. Kimi via OpenCode) send reasoning
* content as `field=text` deltas, with `part.updated type=reasoning` events
* marking the boundaries. When true, text deltas are routed to the reasoning
* buffer instead of being emitted as visible text.
*/
private inReasoningPhase = false
constructor(workingDir: string, opts?: Partial<OpenCodeProcessOptions>) {
super()
this.workingDir = workingDir
this.sessionId = opts?.sessionId || randomUUID()
this.opencodeSessionId = opts?.opencodeSessionId || null
this.model = opts?.model
this.permissionMode = opts?.permissionMode
this.recentOutputText = opts?.recentOutputText ?? ''
}
/** Connect to the OpenCode server, create a session, and subscribe to SSE events. */
start(): void {
if (this.alive) return
this.alive = true
// Startup timeout
this.startupTimer = setTimeout(() => {
this.startupTimer = null
if (this.alive) {
this.emit('error', 'OpenCode process failed to initialize within 60 seconds')
this.stop()
}
}, 60_000)
void this.initialize().catch((err) => {
this.emit('error', `OpenCode initialization failed: ${err instanceof Error ? err.message : String(err)}`)
this.stop()
})
}
private async initialize(): Promise<void> {
const baseUrl = await ensureOpenCodeServer(this.workingDir)
// Create or resume a session — must happen BEFORE SSE subscription
// so that this.opencodeSessionId is set and the session ID filter
// guards in handleSSEEvent() are active (prevents cross-session leakage).
const permission = permissionRulesetFor(this.permissionMode)
if (this.opencodeSessionId) {
// Resume existing session — reconnect to SSE, but push the current
// permission ruleset since the mode may have changed since creation
// (mode changes restart the process with resume).
if (permission) {
try {
const patchRes = await fetch(`${baseUrl}/session/${this.opencodeSessionId}`, {
method: 'PATCH',
headers: {
...authHeaders(),
'Content-Type': 'application/json',
'x-opencode-directory': this.workingDir,
},
body: JSON.stringify({ permission }),
signal: AbortSignal.timeout(10_000),
})
if (!patchRes.ok) {
console.warn(`[opencode] Failed to update session permissions: HTTP ${patchRes.status}`)
}
} catch (err) {
console.warn('[opencode] Failed to update session permissions:', err)
}
}
// Hydrate any assistant response that completed while we were detached
// (backend crash/restart mid-turn) — non-fatal on failure.
void this.hydrateMissedTail(baseUrl)
} else {
const createRes = await fetch(`${baseUrl}/session`, {
method: 'POST',
headers: {
...authHeaders(),
'Content-Type': 'application/json',
'x-opencode-directory': this.workingDir,
},
body: JSON.stringify({
title: `Codekin session ${this.sessionId.slice(0, 8)}`,
...(permission ? { permission } : {}),
}),
})
if (!createRes.ok) {
throw new Error(`Failed to create OpenCode session: ${createRes.status} ${await createRes.text()}`)
}
const data = await createRes.json() as { id: string }
this.opencodeSessionId = data.id
}
// Load available commands (slash commands / skills / MCP prompts) so
// sendMessage can route `/name args` input to the command endpoint.
// Non-fatal — command routing simply stays disabled on failure.
void this.loadCommands(baseUrl)
// Subscribe to SSE events AFTER opencodeSessionId is set so session
// filtering is active from the first event received.
this.subscribeToEvents(baseUrl)
// Clear startup timer and emit init
if (this.startupTimer) {
clearTimeout(this.startupTimer)
this.startupTimer = null
}
// Model is stored as "providerID/modelID" — show everything after the first slash.
// Only emit system_init when we have an explicit model. If model is undefined,
// the frontend's model validation effect will call setModel shortly, which
// triggers a restart with the correct model — no point showing a placeholder.
if (this.model) {
const modelName = this.model.includes('/') ? this.model.slice(this.model.indexOf('/') + 1) : this.model
this.emit('system_init', modelName)
}
// Surface plan mode in the UI — OpenCode plan mode is implemented by
// selecting the read-only `plan` agent on every prompt this session.
if (this.permissionMode === 'plan') {
this.emit('planning_mode', true)
}
}
/** Fetch the command list from the server (used for slash-command routing). */
private async loadCommands(baseUrl: string): Promise<void> {
try {
const res = await fetch(`${baseUrl}/command`, {
headers: {
...authHeaders(),
'x-opencode-directory': this.workingDir,
},
signal: AbortSignal.timeout(10_000),
})
if (!res.ok) return
const data = await res.json() as OpenCodeCommandInfo[]
if (Array.isArray(data)) {
this.commands = new Map(data.map(c => [c.name, c]))
}
} catch (err) {
console.warn('[opencode] Failed to load command list:', err)
}
}
/** Subscribe to the OpenCode SSE event stream and map events to CodingProcess events. */
private subscribeToEvents(initialBaseUrl: string): void {
this.abortController = new AbortController()
let reconnectDelay = 1000
const MAX_RECONNECT_DELAY = 30_000
const MAX_RECONNECT_ATTEMPTS = 20
let reconnectAttempts = 0
let firstConnect = true
/** Count a failed attempt and schedule a retry. Returns false when retries are exhausted. */
const scheduleReconnect = (reason: string): boolean => {
reconnectAttempts++
if (reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
this.emit('error', `SSE reconnect failed after ${MAX_RECONNECT_ATTEMPTS} attempts (${reason})`)
this.stop()
return false
}
console.warn(`[opencode-sse] ${reason}, reconnecting in ${reconnectDelay / 1000}s (attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})...`)
setTimeout(() => { void connectSSE() }, reconnectDelay)
reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY)
return true
}
const connectSSE = async () => {
if (!this.alive) return
// Re-resolve the base URL on every attempt: if the shared OpenCode
// server died, it respawns on a NEW random port — reconnecting to the
// old URL would never succeed. ensureOpenCodeServer respawns the server
// if needed and returns the current URL. The first connect reuses the
// URL from initialize() to avoid a redundant health check.
let baseUrl = initialBaseUrl
if (!firstConnect) {
try {
baseUrl = await ensureOpenCodeServer(this.workingDir)
} catch (err) {
if (this.alive) {
scheduleReconnect(`Server unavailable (${err instanceof Error ? err.message : String(err)})`)
}
return
}
if (!this.alive) return
}
firstConnect = false
void fetch(`${baseUrl}/event`, {
headers: {
...authHeaders(),
Accept: 'text/event-stream',
'x-opencode-directory': this.workingDir,
},
signal: this.abortController!.signal,
}).then(async (res) => {
if (!res.ok || !res.body) {
if (this.alive) {
scheduleReconnect(`Non-2xx ${res.status}`)
}
return
}
// Reset backoff on successful connection
reconnectDelay = 1000
reconnectAttempts = 0
// If a turn was in flight across the reconnect, the completion event
// may have been lost while disconnected — resync immediately.
if (!this.turnComplete && this.turnWatchdog) {
void this.checkTurnLiveness(true)
}
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buffer = ''
while (this.alive) {
const { done, value } = await reader.read()
if (done) break
buffer += decoder.decode(value, { stream: true })
const lines = buffer.split('\n')
buffer = lines.pop() || ''
let currentData = ''
for (const line of lines) {
if (line.startsWith('data: ')) {
currentData += line.slice(6)
} else if (line === '' && currentData) {
try {
const event = JSON.parse(currentData) as OpenCodeSSEEvent
this.handleSSEEvent(event)
} catch {
// Ignore unparseable SSE data
}
currentData = ''
}
}
}
// Clean EOF — reconnect if still alive (server restart, proxy timeout, etc.)
if (this.alive) {
scheduleReconnect('Stream closed cleanly')
}
}).catch((err: unknown) => {
if (err instanceof Error && err.name === 'AbortError') return
if (this.alive) {
scheduleReconnect(`Connection lost (${err instanceof Error ? err.message : String(err)})`)
}
})
}
void connectSSE()
}
/**
* Check whether an SSE event belongs to this process's OpenCode session.
* Returns true if the event should be processed, false if it should be skipped.
* Rejects events when opencodeSessionId is not yet set (init window) to prevent
* cross-session leakage on the shared SSE stream.
*/
private isOwnSession(properties: Record<string, unknown>): boolean {
const sessionID = properties.sessionID as string | undefined
// If we don't have our session ID yet, reject everything to prevent
// cross-session leakage during the initialization window.
if (!this.opencodeSessionId) return false
// If event has no session ID, accept (server-level event)
if (!sessionID) return true
return sessionID === this.opencodeSessionId
}
/** Flush any buffered text deltas that haven't been emitted yet (e.g. turn ended before buffer threshold). */
private flushDeltaBuffer(): void {
if (!this.deltaBufferFlushed && this.deltaBuffer) {
this.deltaBufferFlushed = true
if (this.lastUserInput && this.deltaBuffer.startsWith(this.lastUserInput)) {
const remainder = this.deltaBuffer.slice(this.lastUserInput.length)
if (remainder) this.emit('text', remainder)
} else {
this.emit('text', this.deltaBuffer)
}
this.deltaBuffer = ''
}
}
/**
* Mark the current turn as complete: release the latch, flush any buffered
* text, stop the stall watchdog, and emit the result event. Idempotent.
*/
private completeTurn(): void {
if (this.turnComplete) return
this.turnComplete = true
this.turnInFlight = false
this.clearTurnWatchdog()
this.flushDeltaBuffer()
this.emit('result', '', false)
// Send the next queued message (received mid-turn) after result handlers run.
const next = this.pendingMessages.shift()
if (next !== undefined && this.alive) {
setImmediate(() => { this.sendMessage(next) })
}
}
/** Map an OpenCode SSE event to CodingProcess events. */
private handleSSEEvent(event: OpenCodeSSEEvent): void {
const { type, properties } = event
// Track liveness of this session's event flow for the turn watchdog.
// Only count events explicitly scoped to our session (or a subagent child
// session) — server-level events (heartbeats etc.) say nothing about our
// turn's progress.
const evtSessionID = properties.sessionID as string | undefined
if (evtSessionID && (evtSessionID === this.opencodeSessionId || this.childSessionIds.has(evtSessionID))) {
this.lastSessionEventTime = Date.now()
}
switch (type) {
// Delta events carry the actual streaming text content
case 'message.part.delta': {
if (!this.isOwnSession(properties)) break
const field = properties.field as string | undefined
const delta = properties.delta as string | undefined
if (process.env.CODEKIN_DEBUG_SSE) {
console.log(`[opencode-sse] delta field=${field} len=${delta?.length ?? 0} text=${delta?.slice(0, 80)}`)
}
if (field === 'text' && delta) {
this.receivedDeltas = true
// Some providers (e.g. Kimi via OpenCode) send reasoning content as
// field=text deltas. When inReasoningPhase is set (by a preceding
// part.updated type=reasoning event), route to reasoning buffer.
if (this.inReasoningPhase) {
this.reasoningBuffer += delta
if (this.reasoningBuffer.length > 20 && !this.emittedReasoningSummary) {
this.emittedReasoningSummary = true
const match = this.reasoningBuffer.match(/^(.+?[.!?\n])/)
const summary = match && match[1].length <= 120
? match[1].replace(/\n/g, ' ').trim()
: this.reasoningBuffer.slice(0, 80).trim()
this.emit('thinking', summary)
}
break
}
// Buffer initial deltas to detect and strip user echo prefix.
// Some providers echo the user message at the start of the assistant
// response, which causes duplicate display.
if (!this.deltaBufferFlushed && this.lastUserInput) {
this.deltaBuffer += delta
if (this.deltaBuffer.length >= this.lastUserInput.length) {
this.deltaBufferFlushed = true
if (this.deltaBuffer.startsWith(this.lastUserInput)) {
const remainder = this.deltaBuffer.slice(this.lastUserInput.length)
if (remainder) this.emit('text', remainder)
} else {
this.emit('text', this.deltaBuffer)
}
this.deltaBuffer = ''
}
// Still buffering — don't emit yet
} else {
this.emit('text', delta)
}
} else if (field === 'reasoning' && delta) {
// Accumulate reasoning deltas and emit a thinking summary once we
// have enough content, so the UI shows a thinking indicator during
// streaming (not only when message.part.updated arrives later).
this.reasoningBuffer += delta
if (this.reasoningBuffer.length > 20 && !this.emittedReasoningSummary) {
this.emittedReasoningSummary = true
const match = this.reasoningBuffer.match(/^(.+?[.!?\n])/)
const summary = match && match[1].length <= 120
? match[1].replace(/\n/g, ' ').trim()
: this.reasoningBuffer.slice(0, 80).trim()
this.emit('thinking', summary)
}
}
break
}
case 'message.part.updated': {
const part = properties.part as OpenCodeMessagePart | undefined
if (!part) break
// Only process events for our session. Subagent child sessions get
// their tool activity surfaced (text/reasoning is internal to the
// subagent and would pollute the main transcript).
if (!this.isOwnSession(properties)) {
if (evtSessionID && this.childSessionIds.has(evtSessionID) && part.type === 'tool') {
this.handleChildToolPart(part)
}
break
}
if (process.env.CODEKIN_DEBUG_SSE) {
console.log(`[opencode-sse] part.updated type=${part.type} len=${part.text?.length ?? 0} text=${part.text?.slice(0, 80)} receivedDeltas=${this.receivedDeltas} emittedPartText=${this.emittedPartText}`)
}
switch (part.type) {
case 'text': {
// A text part.updated signals that text deltas are now actual
// response text, not reasoning. Clear the reasoning phase flag.
if (this.inReasoningPhase) {
this.inReasoningPhase = false
}
// Text may arrive via message.part.delta (streaming) or as full
// content here (OpenCode >=1.4 message.updated). Only emit if we
// haven't already streamed it via delta events or emitted it from
// an earlier message.part.updated event.
if (part.text && !this.receivedDeltas && !this.emittedPartText) {
this.emittedPartText = true
// Strip user echo prefix if the full text starts with the last input
let text = part.text
if (this.lastUserInput && text.startsWith(this.lastUserInput)) {
text = text.slice(this.lastUserInput.length)
}
if (text) this.emit('text', text)
}
break
}
case 'reasoning': {
// A reasoning part.updated signals that subsequent text deltas
// are reasoning content, not visible text. Set the phase flag so
// the delta handler routes them to the reasoning buffer.
this.inReasoningPhase = true
// OpenCode uses 'text' field, not 'content'. Reasoning may be
// empty or encrypted (e.g. OpenAI models). Only emit if present.
const content = part.text || ''
if (content.length > 20 && !this.emittedReasoningSummary) {
this.emittedReasoningSummary = true
const match = content.match(/^(.+?[.!?\n])/)
const summary = match && match[1].length <= 120
? match[1].replace(/\n/g, ' ').trim()
: content.slice(0, 80).trim()
this.emit('thinking', summary)
}
break
}
case 'tool': {
// Tool state is an object {status, input, output, time, ...}, not a string
const toolName = part.tool || 'unknown'
const status = part.state?.status
if (status === 'running') {
const inputStr = part.state?.input ? summarizeToolInput(toolName, part.state.input) : undefined
this.emit('tool_active', toolName, inputStr)
// Detect task/todo tool calls and emit todo_update
if (part.state?.input && this.handleTaskTool(toolName, part.state.input)) {
this.emit('todo_update', Array.from(this.tasks.values(), t => ({ ...t })))
}
} else if (status === 'completed') {
// Also check for task tools at completion (some providers only
// populate input at this stage, not during 'running')
if (part.state?.input && this.handleTaskTool(toolName, part.state.input)) {
this.emit('todo_update', Array.from(this.tasks.values(), t => ({ ...t })))
}
const output = part.state?.output
const summary = output ? output.slice(0, 200) : undefined
this.emit('tool_done', toolName, summary)
if (output) {
const truncated = output.length > 2000
? output.slice(0, 2000) + `\n… (truncated, ${output.length} chars total)`
: output
this.emit('tool_output', truncated, false)
}
} else if (status === 'error') {
const errMsg = part.state?.error || 'unknown'
this.emit('tool_done', toolName, `Error: ${errMsg}`)
this.emit('tool_output', errMsg, true)
}
// 'pending' status — tool call parsed but not yet executing; no action needed
break
}
case 'step-finish': {
// Agentic iteration boundary — any buffered text below the echo
// threshold belongs to the finished step; flush it now instead of
// holding it until turn end.
this.flushDeltaBuffer()
break
}
// step-start is an agentic iteration boundary — no mapping needed
}
break
}
case 'session.status': {
if (!this.isOwnSession(properties)) break
// Status may be a string ('idle') or object ({ type: 'idle' }) depending on OpenCode version
const status = properties.status
const statusType = typeof status === 'string' ? status : (status as { type?: string } | undefined)?.type
if (statusType === 'idle') {
this.completeTurn()
}
break
}
case 'session.error': {
if (!this.isOwnSession(properties)) break
const error = properties.error as { message?: string } | undefined
this.emit('error', error?.message || 'Unknown OpenCode error')
break
}
case 'permission.asked': {
if (!this.isOwnSession(properties)) break
const requestId = properties.id as string | undefined
if (!requestId) {
console.error('[opencode] permission.asked event missing required id field')
break
}
// Real format: properties.permission is the type (e.g. "external_directory"),
// properties.metadata has details (filepath, parentDir), properties.patterns
// has the glob patterns being requested. No direct tool name — use permission type.
const permissionType = properties.permission as string || 'unknown'
const metadata = properties.metadata as Record<string, unknown> || {}
const patterns = properties.patterns as string[] || []
const input: Record<string, unknown> = {
permission: permissionType,
...metadata,
patterns,
}
// Auto-approve for headless sessions (webhook/workflow)
if (this.permissionMode === 'bypassPermissions' || this.permissionMode === 'dangerouslySkipPermissions') {
void this.replyToPermission(requestId, 'always')
return
}
// Emit as control_request for SessionManager to handle
this.emit('control_request', requestId, permissionType, input)
break
}
// message.completed signals that the model has finished its response
case 'message.completed': {
if (!this.isOwnSession(properties)) break
this.completeTurn()
break
}
// session.updated may carry idle status in some OpenCode versions.
// session.created/session.updated also announce subagent child sessions
// (parentID = our session) which we track to surface their tool activity.
case 'session.created':
case 'session.updated': {
const session = (properties.info ?? properties.session) as Record<string, unknown> | undefined
const sessId = session?.id as string | undefined
const parentID = session?.parentID as string | undefined
if (sessId && parentID && parentID === this.opencodeSessionId && !this.childSessionIds.has(sessId)) {
this.childSessionIds.add(sessId)
const title = typeof session?.title === 'string' && session.title ? session.title : 'subagent'
this.emit('tool_active', 'Task', title)
}
if (!this.isOwnSession(properties)) break