Open History to see the last commit
1import {
2 EventId,
3 type OpenCodeSettings,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 type ProviderRuntimeEvent,
7 type ProviderSession,
8 RuntimeItemId,
9 RuntimeRequestId,
10 ThreadId,
11 type ToolLifecycleItemType,
12 TurnId,
13 type UserInputQuestion,
14} from "@v12/contracts";
15import * as Cause from "effect/Cause";
16import * as Crypto from "effect/Crypto";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as Queue from "effect/Queue";
21import * as Ref from "effect/Ref";
22import * as Scope from "effect/Scope";
23import * as Stream from "effect/Stream";
24import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2";
25import { getModelSelectionStringOptionValue } from "@v12/shared/model";
26
27import { resolveAttachmentPath } from "../../attachmentStore.ts";
28import { ServerConfig } from "../../config.ts";
29import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
30import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
31import {
32 ProviderAdapterProcessError,
33 ProviderAdapterRequestError,
34 ProviderAdapterSessionClosedError,
35 ProviderAdapterSessionNotFoundError,
36 ProviderAdapterValidationError,
37} from "../Errors.ts";
38import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
39import {
40 buildOpenCodePermissionRules,
41 OpenCodeRuntime,
42 OpenCodeRuntimeError,
43 openCodeQuestionId,
44 openCodeRuntimeErrorDetail,
45 parseOpenCodeModelSlug,
46 runOpenCodeSdk,
47 toOpenCodeFileParts,
48 toOpenCodePermissionReply,
49 toOpenCodeQuestionAnswers,
50 type OpenCodeServerConnection,
51} from "../opencodeRuntime.ts";
52import * as Option from "effect/Option";
53
54const PROVIDER = ProviderDriverKind.make("opencode");
55
56interface OpenCodeTurnSnapshot {
57 readonly id: TurnId;
58 readonly items: Array<unknown>;
59}
60
61type OpenCodeSubscribedEvent =
62 Awaited<ReturnType<OpencodeClient["event"]["subscribe"]>> extends {
63 readonly stream: AsyncIterable<infer TEvent>;
64 }
65 ? TEvent
66 : never;
67
68interface OpenCodeSessionContext {
69 session: ProviderSession;
70 readonly client: OpencodeClient;
71 readonly server: OpenCodeServerConnection;
72 readonly directory: string;
73 readonly openCodeSessionId: string;
74 readonly pendingPermissions: Map<string, PermissionRequest>;
75 readonly pendingQuestions: Map<string, QuestionRequest>;
76 readonly messageRoleById: Map<string, "user" | "assistant">;
77 readonly partById: Map<string, Part>;
78 readonly emittedTextByPartId: Map<string, string>;
79 readonly completedAssistantPartIds: Set<string>;
80 readonly turns: Array<OpenCodeTurnSnapshot>;
81 activeTurnId: TurnId | undefined;
82 activeAgent: string | undefined;
83 activeVariant: string | undefined;
84 /**
85 * One-shot guard flipped by `stopOpenCodeContext` / `emitUnexpectedExit`.
86 * The session lifecycle is owned by `sessionScope`; this Ref exists only
87 * so concurrent callers can race the transition safely via `getAndSet`.
88 */
89 readonly stopped: Ref.Ref<boolean>;
90 /**
91 * Sole lifecycle handle for the session. Closing this scope:
92 * - aborts the `AbortController` registered as a finalizer
93 * (cancels the in-flight `event.subscribe` fetch),
94 * - interrupts the event-pump and server-exit fibers forked
95 * via `Effect.forkIn(sessionScope)`,
96 * - tears down the OpenCode server process for scope-owned servers.
97 */
98 readonly sessionScope: Scope.Closeable;
99}
100
101export interface OpenCodeAdapterLiveOptions {
102 readonly instanceId?: ProviderInstanceId;
103 readonly environment?: NodeJS.ProcessEnv;
104 readonly nativeEventLogPath?: string;
105 readonly nativeEventLogger?: EventNdjsonLogger;
106}
107
108const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
109
110/**
111 * Map a tagged OpenCodeRuntimeError produced by {@link runOpenCodeSdk} into
112 * the adapter-boundary `ProviderAdapterRequestError`. SDK-method-level call
113 * sites pipe through this in `Effect.mapError` so they never build the error
114 * shape by hand.
115 */
116const toRequestError = (cause: OpenCodeRuntimeError): ProviderAdapterRequestError =>
117 new ProviderAdapterRequestError({
118 provider: PROVIDER,
119 method: cause.operation,
120 detail: cause.detail,
121 cause: cause.cause,
122 });
123
124/**
125 * Map a `Cause.squash`-ed failure into a `ProviderAdapterProcessError`. The
126 * typed cause is usually an `OpenCodeRuntimeError` (from {@link runOpenCodeSdk}),
127 * in which case we preserve its `detail`; otherwise we fall back to
128 * {@link openCodeRuntimeErrorDetail} for unknown causes (defects, etc.).
129 */
130const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProcessError =>
131 new ProviderAdapterProcessError({
132 provider: PROVIDER,
133 threadId,
134 detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),
135 cause,
136 });
137
138type EventBaseInput = {
139 readonly threadId: ThreadId;
140 readonly turnId?: TurnId | undefined;
141 readonly itemId?: string | undefined;
142 readonly requestId?: string | undefined;
143 readonly createdAt?: string | undefined;
144 readonly raw?: unknown;
145};
146
147function toToolLifecycleItemType(toolName: string): ToolLifecycleItemType {
148 const normalized = toolName.toLowerCase();
149 if (normalized.includes("bash") || normalized.includes("command")) {
150 return "command_execution";
151 }
152 if (
153 normalized.includes("edit") ||
154 normalized.includes("write") ||
155 normalized.includes("patch") ||
156 normalized.includes("multiedit")
157 ) {
158 return "file_change";
159 }
160 if (normalized.includes("web")) {
161 return "web_search";
162 }
163 if (normalized.includes("mcp")) {
164 return "mcp_tool_call";
165 }
166 if (normalized.includes("image")) {
167 return "image_view";
168 }
169 if (
170 normalized.includes("task") ||
171 normalized.includes("agent") ||
172 normalized.includes("subtask")
173 ) {
174 return "collab_agent_tool_call";
175 }
176 return "dynamic_tool_call";
177}
178
179function mapPermissionToRequestType(
180 permission: string,
181): "command_execution_approval" | "file_read_approval" | "file_change_approval" | "unknown" {
182 switch (permission) {
183 case "bash":
184 return "command_execution_approval";
185 case "read":
186 return "file_read_approval";
187 case "edit":
188 return "file_change_approval";
189 default:
190 return "unknown";
191 }
192}
193
194function mapPermissionDecision(reply: "once" | "always" | "reject"): string {
195 switch (reply) {
196 case "once":
197 return "accept";
198 case "always":
199 return "acceptForSession";
200 case "reject":
201 default:
202 return "decline";
203 }
204}
205
206function resolveTurnSnapshot(
207 context: OpenCodeSessionContext,
208 turnId: TurnId,
209): OpenCodeTurnSnapshot {
210 const existing = context.turns.find((turn) => turn.id === turnId);
211 if (existing) {
212 return existing;
213 }
214
215 const created: OpenCodeTurnSnapshot = { id: turnId, items: [] };
216 context.turns.push(created);
217 return created;
218}
219
220function appendTurnItem(
221 context: OpenCodeSessionContext,
222 turnId: TurnId | undefined,
223 item: unknown,
224): void {
225 if (!turnId) {
226 return;
227 }
228 resolveTurnSnapshot(context, turnId).items.push(item);
229}
230
231function ensureSessionContext(
232 sessions: ReadonlyMap<ThreadId, OpenCodeSessionContext>,
233 threadId: ThreadId,
234): OpenCodeSessionContext {
235 const session = sessions.get(threadId);
236 if (!session) {
237 throw new ProviderAdapterSessionNotFoundError({
238 provider: PROVIDER,
239 threadId,
240 });
241 }
242 // `ensureSessionContext` is a sync gate used from both sync helpers and
243 // Effect bodies. `Ref.getUnsafe` is an atomic read of the backing cell —
244 // no fiber suspension required, which keeps this callable everywhere.
245 if (Ref.getUnsafe(session.stopped)) {
246 throw new ProviderAdapterSessionClosedError({
247 provider: PROVIDER,
248 threadId,
249 });
250 }
251 return session;
252}
253
254function normalizeQuestionRequest(request: QuestionRequest): ReadonlyArray<UserInputQuestion> {
255 return request.questions.map((question, index) => ({
256 id: openCodeQuestionId(index, question),
257 header: question.header,
258 question: question.question,
259 options: question.options.map((option) => ({
260 label: option.label,
261 description: option.description,
262 })),
263 ...(question.multiple ? { multiSelect: true } : {}),
264 }));
265}
266
267function resolveTextStreamKind(part: Part | undefined): "assistant_text" | "reasoning_text" {
268 return part?.type === "reasoning" ? "reasoning_text" : "assistant_text";
269}
270
271function textFromPart(part: Part): string | undefined {
272 switch (part.type) {
273 case "text":
274 case "reasoning":
275 return part.text;
276 default:
277 return undefined;
278 }
279}
280
281function commonPrefixLength(left: string, right: string): number {
282 let index = 0;
283 while (index < left.length && index < right.length && left[index] === right[index]) {
284 index += 1;
285 }
286 return index;
287}
288
289function resolveLatestAssistantText(previousText: string | undefined, nextText: string): string {
290 if (previousText && previousText.length > nextText.length && previousText.startsWith(nextText)) {
291 return previousText;
292 }
293 return nextText;
294}
295
296export function mergeOpenCodeAssistantText(
297 previousText: string | undefined,
298 nextText: string,
299): {
300 readonly latestText: string;
301 readonly deltaToEmit: string;
302} {
303 const latestText = resolveLatestAssistantText(previousText, nextText);
304 return {
305 latestText,
306 deltaToEmit: latestText.slice(commonPrefixLength(previousText ?? "", latestText)),
307 };
308}
309
310export function appendOpenCodeAssistantTextDelta(
311 previousText: string,
312 delta: string,
313): {
314 readonly nextText: string;
315 readonly deltaToEmit: string;
316} {
317 return {
318 nextText: previousText + delta,
319 deltaToEmit: delta,
320 };
321}
322
323const isoFromEpochMs = (value: number) =>
324 DateTime.make(value).pipe(
325 Option.match({
326 onNone: () => undefined,
327 onSome: DateTime.formatIso,
328 }),
329 );
330
331function messageRoleForPart(
332 context: OpenCodeSessionContext,
333 part: Pick<Part, "messageID" | "type">,
334): "assistant" | "user" | undefined {
335 const known = context.messageRoleById.get(part.messageID);
336 if (known) {
337 return known;
338 }
339 return part.type === "tool" ? "assistant" : undefined;
340}
341
342function detailFromToolPart(part: Extract<Part, { type: "tool" }>): string | undefined {
343 switch (part.state.status) {
344 case "completed":
345 return part.state.output;
346 case "error":
347 return part.state.error;
348 case "running":
349 return part.state.title;
350 default:
351 return undefined;
352 }
353}
354
355function toolStateCreatedAt(part: Extract<Part, { type: "tool" }>): string | undefined {
356 switch (part.state.status) {
357 case "running":
358 return isoFromEpochMs(part.state.time.start);
359 case "completed":
360 case "error":
361 return isoFromEpochMs(part.state.time.end);
362 default:
363 return undefined;
364 }
365}
366
367function sessionErrorMessage(error: unknown): string {
368 if (!error || typeof error !== "object") {
369 return "OpenCode session failed.";
370 }
371 const data = "data" in error && error.data && typeof error.data === "object" ? error.data : null;
372 const message = data && "message" in data ? data.message : null;
373 return typeof message === "string" && message.trim().length > 0
374 ? message
375 : "OpenCode session failed.";
376}
377
378function updateProviderSession(
379 context: OpenCodeSessionContext,
380 patch: Partial<ProviderSession>,
381 options?: {
382 readonly clearActiveTurnId?: boolean;
383 readonly clearLastError?: boolean;
384 },
385): Effect.Effect<ProviderSession> {
386 return Effect.gen(function* () {
387 const updatedAt = yield* nowIso;
388 const nextSession = {
389 ...context.session,
390 ...patch,
391 updatedAt,
392 } as ProviderSession & Record<string, unknown>;
393 const mutableSession = nextSession as Record<string, unknown>;
394 if (options?.clearActiveTurnId) {
395 delete mutableSession.activeTurnId;
396 }
397 if (options?.clearLastError) {
398 delete mutableSession.lastError;
399 }
400 context.session = nextSession;
401 return nextSession;
402 });
403}
404
405const stopOpenCodeContext = Effect.fn("stopOpenCodeContext")(function* (
406 context: OpenCodeSessionContext,
407) {
408 // Race-safe one-shot: first caller flips the flag, everyone else no-ops.
409 if (yield* Ref.getAndSet(context.stopped, true)) {
410 return false;
411 }
412
413 // Best-effort remote abort. The scope close below tears down the local
414 // handles (event-pump fiber, server-exit fiber, event-subscribe fetch),
415 // but we still want to tell OpenCode that this session is done.
416 yield* runOpenCodeSdk("session.abort", () =>
417 context.client.session.abort({ sessionID: context.openCodeSessionId }),
418 ).pipe(Effect.ignore({ log: true }));
419
420 // Closing the session scope interrupts every fiber forked into it and
421 // runs each finalizer we registered — the `AbortController.abort()` call,
422 // the child-process termination, etc.
423 yield* Scope.close(context.sessionScope, Exit.void);
424 return true;
425});
426
427export function makeOpenCodeAdapter(
428 openCodeSettings: OpenCodeSettings,
429 options?: OpenCodeAdapterLiveOptions,
430) {
431 return Effect.gen(function* () {
432 const boundInstanceId = options?.instanceId ?? ProviderInstanceId.make("opencode");
433 const serverConfig = yield* ServerConfig;
434 const openCodeRuntime = yield* OpenCodeRuntime;
435 const crypto = yield* Crypto.Crypto;
436 const nativeEventLogger =
437 options?.nativeEventLogger ??
438 (options?.nativeEventLogPath !== undefined
439 ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
440 stream: "native",
441 })
442 : undefined);
443 // Only close loggers we created. If the caller passed one in via
444 // `options.nativeEventLogger`, they own its lifecycle.
445 const managedNativeEventLogger =
446 options?.nativeEventLogger === undefined ? nativeEventLogger : undefined;
447 const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
448 const sessions = new Map<ThreadId, OpenCodeSessionContext>();
449 const randomUUIDv4 = crypto.randomUUIDv4.pipe(
450 Effect.mapError(
451 (cause) =>
452 new ProviderAdapterRequestError({
453 provider: PROVIDER,
454 method: "crypto/randomUUIDv4",
455 detail: "Failed to generate OpenCode runtime identifier.",
456 cause,
457 }),
458 ),
459 );
460 const buildEventBase = (input: EventBaseInput) =>
461 Effect.all({
462 eventId: randomUUIDv4.pipe(Effect.map(EventId.make)),
463 createdAt: input.createdAt === undefined ? nowIso : Effect.succeed(input.createdAt),
464 }).pipe(
465 Effect.map(({ eventId, createdAt }) => ({
466 eventId,
467 provider: PROVIDER,
468 threadId: input.threadId,
469 createdAt,
470 ...(input.turnId ? { turnId: input.turnId } : {}),
471 ...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),
472 ...(input.requestId ? { requestId: RuntimeRequestId.make(input.requestId) } : {}),
473 ...(input.raw !== undefined
474 ? {
475 raw: {
476 source: "opencode.sdk.event" as const,
477 payload: input.raw,
478 },
479 }
480 : {}),
481 })),
482 );
483
484 // Layer-level finalizer: when the adapter layer shuts down, stop every
485 // session. Each session's `Scope.close` tears down its spawned OpenCode
486 // server (via the `ChildProcessSpawner` finalizer installed in
487 // `startOpenCodeServerProcess`) and interrupts the forked event/exit
488 // fibers. Consumers that can't reason about Effect scopes therefore
489 // cannot leak OpenCode child processes by forgetting to call `stopAll`.
490 yield* Effect.addFinalizer(() =>
491 Effect.gen(function* () {
492 const contexts = [...sessions.values()];
493 sessions.clear();
494 // `ignoreCause` swallows both typed failures (none here) and defects
495 // from throwing scope finalizers so a sibling's death can't interrupt
496 // the remaining cleanups.
497 yield* Effect.forEach(
498 contexts,
499 (context) => Effect.ignoreCause(stopOpenCodeContext(context)),
500 { concurrency: "unbounded", discard: true },
501 );
502 // Close the logger AFTER session teardown so any final lifecycle
503 // events emitted during shutdown still get written. `close` flushes
504 // the `Logger.batched` window and closes each per-thread
505 // `RotatingFileSink` handle owned by the logger's internal scope.
506 if (managedNativeEventLogger !== undefined) {
507 yield* managedNativeEventLogger.close();
508 }
509 }).pipe(Effect.ensuring(Queue.shutdown(runtimeEvents))),
510 );
511
512 const emit = (event: ProviderRuntimeEvent) =>
513 Queue.offer(runtimeEvents, event).pipe(Effect.asVoid);
514 const writeNativeEvent = (
515 threadId: ThreadId,
516 event: {
517 readonly observedAt: string;
518 readonly event: Record<string, unknown>;
519 },
520 ) => (nativeEventLogger ? nativeEventLogger.write(event, threadId) : Effect.void);
521 const writeNativeEventBestEffort = (
522 threadId: ThreadId,
523 event: {
524 readonly observedAt: string;
525 readonly event: Record<string, unknown>;
526 },
527 ) => writeNativeEvent(threadId, event).pipe(Effect.catchCause(() => Effect.void));
528
529 const emitUnexpectedExit = Effect.fn("emitUnexpectedExit")(function* (
530 context: OpenCodeSessionContext,
531 message: string,
532 ) {
533 // Atomic one-shot: two fibers can race here (the event-pump on stream
534 // failure and the server-exit watcher). `getAndSet` flips the flag in
535 // a single step so the loser observes `true` and returns; a plain
536 // `Ref.get` would let both racers slip past and emit duplicates.
537 if (yield* Ref.getAndSet(context.stopped, true)) {
538 return;
539 }
540 const turnId = context.activeTurnId;
541 sessions.delete(context.session.threadId);
542 // Emit lifecycle events BEFORE tearing down the scope. Both call sites
543 // run this inside a fiber forked via `Effect.forkIn(context.sessionScope)`;
544 // closing that scope triggers the fiber-interrupt finalizer, so any
545 // subsequent yield point would unwind and silently drop these emits.
546 yield* emit({
547 ...(yield* buildEventBase({
548 threadId: context.session.threadId,
549 turnId,
550 })),
551 type: "runtime.error",
552 payload: {
553 message,
554 class: "transport_error",
555 },
556 }).pipe(Effect.ignore);
557 yield* emit({
558 ...(yield* buildEventBase({
559 threadId: context.session.threadId,
560 turnId,
561 })),
562 type: "session.exited",
563 payload: {
564 reason: message,
565 recoverable: false,
566 exitKind: "error",
567 },
568 }).pipe(Effect.ignore);
569 // Inline the teardown that `stopOpenCodeContext` would do; we can't
570 // delegate to it because our `getAndSet` above already flipped the
571 // one-shot guard, so the call would no-op.
572 yield* runOpenCodeSdk("session.abort", () =>
573 context.client.session.abort({ sessionID: context.openCodeSessionId }),
574 ).pipe(Effect.ignore({ log: true }));
575 yield* Scope.close(context.sessionScope, Exit.void);
576 });
577
578 /** Emit content.delta and item.completed events for an assistant text part. */
579 const emitAssistantTextDelta = Effect.fn("emitAssistantTextDelta")(function* (
580 context: OpenCodeSessionContext,
581 part: Part,
582 turnId: TurnId | undefined,
583 raw: unknown,
584 ) {
585 const text = textFromPart(part);
586 if (text === undefined) {
587 return;
588 }
589 const previousText = context.emittedTextByPartId.get(part.id);
590 const { latestText, deltaToEmit } = mergeOpenCodeAssistantText(previousText, text);
591 context.emittedTextByPartId.set(part.id, latestText);
592 if (latestText !== text) {
593 context.partById.set(
594 part.id,
595 (part.type === "text" || part.type === "reasoning"
596 ? { ...part, text: latestText }
597 : part) satisfies Part,
598 );
599 }
600 if (deltaToEmit.length > 0) {
601 yield* emit({
602 ...(yield* buildEventBase({
603 threadId: context.session.threadId,
604 turnId,
605 itemId: part.id,
606 createdAt:
607 (part.type === "text" || part.type === "reasoning") && part.time !== undefined
608 ? isoFromEpochMs(part.time.start)
609 : undefined,
610 raw,
611 })),
612 type: "content.delta",
613 payload: {
614 streamKind: resolveTextStreamKind(part),
615 delta: deltaToEmit,
616 },
617 });
618 }
619
620 if (
621 part.type === "text" &&
622 part.time?.end !== undefined &&
623 !context.completedAssistantPartIds.has(part.id)
624 ) {
625 context.completedAssistantPartIds.add(part.id);
626 yield* emit({
627 ...(yield* buildEventBase({
628 threadId: context.session.threadId,
629 turnId,
630 itemId: part.id,
631 createdAt: isoFromEpochMs(part.time.end),
632 raw,
633 })),
634 type: "item.completed",
635 payload: {
636 itemType: "assistant_message",
637 status: "completed",
638 title: "Assistant message",
639 ...(latestText.length > 0 ? { detail: latestText } : {}),
640 },
641 });
642 }
643 });
644
645 const handleSubscribedEvent = Effect.fn("handleSubscribedEvent")(function* (
646 context: OpenCodeSessionContext,
647 event: OpenCodeSubscribedEvent,
648 ) {
649 const payloadSessionId =
650 "properties" in event ? (event.properties as { sessionID?: unknown }).sessionID : undefined;
651 if (payloadSessionId !== context.openCodeSessionId) {
652 return;
653 }
654
655 const turnId = context.activeTurnId;
656 yield* writeNativeEventBestEffort(context.session.threadId, {
657 observedAt: yield* nowIso,
658 event: {
659 provider: PROVIDER,
660 threadId: context.session.threadId,
661 providerThreadId: context.openCodeSessionId,
662 type: event.type,
663 ...(turnId ? { turnId } : {}),
664 payload: event,
665 },
666 });
667
668 switch (event.type) {
669 case "message.updated": {
670 context.messageRoleById.set(event.properties.info.id, event.properties.info.role);
671 if (event.properties.info.role === "assistant") {
672 for (const part of context.partById.values()) {
673 if (part.messageID !== event.properties.info.id) {
674 continue;
675 }
676 yield* emitAssistantTextDelta(context, part, turnId, event);
677 }
678 }
679 break;
680 }
681
682 case "message.removed": {
683 context.messageRoleById.delete(event.properties.messageID);
684 break;
685 }
686
687 case "message.part.delta": {
688 const existingPart = context.partById.get(event.properties.partID);
689 if (!existingPart) {
690 break;
691 }
692 const role = messageRoleForPart(context, existingPart);
693 if (role !== "assistant") {
694 break;
695 }
696 const streamKind = resolveTextStreamKind(existingPart);
697 const delta = event.properties.delta;
698 if (delta.length === 0) {
699 break;
700 }
701 const previousText =
702 context.emittedTextByPartId.get(event.properties.partID) ??
703 textFromPart(existingPart) ??
704 "";
705 const { nextText, deltaToEmit } = appendOpenCodeAssistantTextDelta(previousText, delta);
706 if (deltaToEmit.length === 0) {
707 break;
708 }
709 context.emittedTextByPartId.set(event.properties.partID, nextText);
710 if (existingPart.type === "text" || existingPart.type === "reasoning") {
711 context.partById.set(event.properties.partID, {
712 ...existingPart,
713 text: nextText,
714 });
715 }
716 yield* emit({
717 ...(yield* buildEventBase({
718 threadId: context.session.threadId,
719 turnId,
720 itemId: event.properties.partID,
721 raw: event,
722 })),
723 type: "content.delta",
724 payload: {
725 streamKind,
726 delta: deltaToEmit,
727 },
728 });
729 break;
730 }
731
732 case "message.part.updated": {
733 const part = event.properties.part;
734 context.partById.set(part.id, part);
735 const messageRole = messageRoleForPart(context, part);
736
737 if (messageRole === "assistant") {
738 yield* emitAssistantTextDelta(context, part, turnId, event);
739 }
740
741 if (part.type === "tool") {
742 const itemType = toToolLifecycleItemType(part.tool);
743 const title =
744 part.state.status === "running" ? (part.state.title ?? part.tool) : part.tool;
745 const detail = detailFromToolPart(part);
746 const payload = {
747 itemType,
748 ...(part.state.status === "error"
749 ? { status: "failed" as const }
750 : part.state.status === "completed"
751 ? { status: "completed" as const }
752 : { status: "inProgress" as const }),
753 ...(title ? { title } : {}),
754 ...(detail ? { detail } : {}),
755 data: {
756 tool: part.tool,
757 state: part.state,
758 },
759 };
760 const runtimeEvent: ProviderRuntimeEvent = {
761 ...(yield* buildEventBase({
762 threadId: context.session.threadId,
763 turnId,
764 itemId: part.callID,
765 createdAt: toolStateCreatedAt(part),
766 raw: event,
767 })),
768 type:
769 part.state.status === "pending"
770 ? "item.started"
771 : part.state.status === "completed" || part.state.status === "error"
772 ? "item.completed"
773 : "item.updated",
774 payload,
775 };
776 appendTurnItem(context, turnId, part);
777 yield* emit(runtimeEvent);
778 }
779 break;
780 }
781
782 case "permission.asked": {
783 context.pendingPermissions.set(event.properties.id, event.properties);
784 yield* emit({
785 ...(yield* buildEventBase({
786 threadId: context.session.threadId,
787 turnId,
788 requestId: event.properties.id,
789 raw: event,
790 })),
791 type: "request.opened",
792 payload: {
793 requestType: mapPermissionToRequestType(event.properties.permission),
794 detail:
795 event.properties.patterns.length > 0
796 ? event.properties.patterns.join("\n")
797 : event.properties.permission,
798 args: event.properties.metadata,
799 },
800 });
801 break;
802 }
803
804 case "permission.replied": {
805 context.pendingPermissions.delete(event.properties.requestID);
806 yield* emit({
807 ...(yield* buildEventBase({
808 threadId: context.session.threadId,
809 turnId,
810 requestId: event.properties.requestID,
811 raw: event,
812 })),
813 type: "request.resolved",
814 payload: {
815 requestType: "unknown",
816 decision: mapPermissionDecision(event.properties.reply),
817 },
818 });
819 break;
820 }
821
822 case "question.asked": {
823 context.pendingQuestions.set(event.properties.id, event.properties);
824 yield* emit({
825 ...(yield* buildEventBase({
826 threadId: context.session.threadId,
827 turnId,
828 requestId: event.properties.id,
829 raw: event,
830 })),
831 type: "user-input.requested",
832 payload: {
833 questions: normalizeQuestionRequest(event.properties),
834 },
835 });
836 break;
837 }
838
839 case "question.replied": {
840 const request = context.pendingQuestions.get(event.properties.requestID);
841 context.pendingQuestions.delete(event.properties.requestID);
842 const answers = Object.fromEntries(
843 (request?.questions ?? []).map((question, index) => [
844 openCodeQuestionId(index, question),
845 event.properties.answers[index]?.join(", ") ?? "",
846 ]),
847 );
848 yield* emit({
849 ...(yield* buildEventBase({
850 threadId: context.session.threadId,
851 turnId,
852 requestId: event.properties.requestID,
853 raw: event,
854 })),
855 type: "user-input.resolved",
856 payload: { answers },
857 });
858 break;
859 }
860
861 case "question.rejected": {
862 context.pendingQuestions.delete(event.properties.requestID);
863 yield* emit({
864 ...(yield* buildEventBase({
865 threadId: context.session.threadId,
866 turnId,
867 requestId: event.properties.requestID,
868 raw: event,
869 })),
870 type: "user-input.resolved",
871 payload: { answers: {} },
872 });
873 break;
874 }
875
876 case "session.status": {
877 if (event.properties.status.type === "busy") {
878 yield* updateProviderSession(context, {
879 status: "running",
880 activeTurnId: turnId,
881 });
882 }
883
884 if (event.properties.status.type === "retry") {
885 yield* emit({
886 ...(yield* buildEventBase({
887 threadId: context.session.threadId,
888 turnId,
889 raw: event,
890 })),
891 type: "runtime.warning",
892 payload: {
893 message: event.properties.status.message,
894 detail: event.properties.status,
895 },
896 });
897 break;
898 }
899
900 if (event.properties.status.type === "idle" && turnId) {
901 context.activeTurnId = undefined;
902 yield* updateProviderSession(context, { status: "ready" }, { clearActiveTurnId: true });
903 yield* emit({
904 ...(yield* buildEventBase({
905 threadId: context.session.threadId,
906 turnId,
907 raw: event,
908 })),
909 type: "turn.completed",
910 payload: {
911 state: "completed",
912 },
913 });
914 }
915 break;
916 }
917
918 case "session.error": {
919 const message = sessionErrorMessage(event.properties.error);
920 const activeTurnId = context.activeTurnId;
921 context.activeTurnId = undefined;
922 yield* updateProviderSession(
923 context,
924 {
925 status: "error",
926 lastError: message,
927 },
928 { clearActiveTurnId: true },
929 );
930 if (activeTurnId) {
931 yield* emit({
932 ...(yield* buildEventBase({
933 threadId: context.session.threadId,
934 turnId: activeTurnId,
935 raw: event,
936 })),
937 type: "turn.completed",
938 payload: {
939 state: "failed",
940 errorMessage: message,
941 },
942 });
943 }
944 yield* emit({
945 ...(yield* buildEventBase({
946 threadId: context.session.threadId,
947 raw: event,
948 })),
949 type: "runtime.error",
950 payload: {
951 message,
952 class: "provider_error",
953 detail: event.properties.error,
954 },
955 });
956 break;
957 }
958
959 default:
960 break;
961 }
962 });
963
964 const startEventPump = Effect.fn("startEventPump")(function* (context: OpenCodeSessionContext) {
965 // One AbortController per session scope. The finalizer fires when
966 // the scope closes (explicit stop, unexpected exit, or layer
967 // shutdown) and cancels the in-flight `event.subscribe` fetch so
968 // the async iterable unwinds cleanly.
969 const eventsAbortController = new AbortController();
970 yield* Scope.addFinalizer(
971 context.sessionScope,
972 Effect.sync(() => eventsAbortController.abort()),
973 );
974
975 // Fibers forked into `context.sessionScope` are interrupted
976 // automatically when the scope closes — no bookkeeping required.
977 yield* Effect.flatMap(
978 runOpenCodeSdk("event.subscribe", () =>
979 context.client.event.subscribe(undefined, {
980 signal: eventsAbortController.signal,
981 }),
982 ),
983 (subscription) =>
984 Stream.fromAsyncIterable(
985 subscription.stream,
986 (cause) =>
987 new OpenCodeRuntimeError({
988 operation: "event.subscribe",
989 detail: openCodeRuntimeErrorDetail(cause),
990 cause,
991 }),
992 ).pipe(Stream.runForEach((event) => handleSubscribedEvent(context, event))),
993 ).pipe(
994 Effect.exit,
995 Effect.flatMap((exit) =>
996 Effect.gen(function* () {
997 // Expected paths: caller aborted the fetch or the session
998 // has already been marked stopped. Treat as a clean exit.
999 if (eventsAbortController.signal.aborted || (yield* Ref.get(context.stopped))) {
1000 return;
1001 }
1002 if (Exit.isFailure(exit)) {
1003 yield* emitUnexpectedExit(
1004 context,
1005 openCodeRuntimeErrorDetail(Cause.squash(exit.cause)),
1006 );
1007 }
1008 }),
1009 ),
1010 Effect.forkIn(context.sessionScope),
1011 );
1012
1013 if (!context.server.external && context.server.exitCode !== null) {
1014 yield* context.server.exitCode.pipe(
1015 Effect.flatMap((code) =>
1016 Effect.gen(function* () {
1017 if (yield* Ref.get(context.stopped)) {
1018 return;
1019 }
1020 yield* emitUnexpectedExit(context, `OpenCode server exited unexpectedly (${code}).`);
1021 }),
1022 ),
1023 Effect.forkIn(context.sessionScope),
1024 );
1025 }
1026 });
1027
1028 const startSession: OpenCodeAdapterShape["startSession"] = Effect.fn("startSession")(
1029 function* (input) {
1030 const binaryPath = openCodeSettings.binaryPath;
1031 const serverUrl = openCodeSettings.serverUrl;
1032 const serverPassword = openCodeSettings.serverPassword;
1033 const directory = input.cwd ?? serverConfig.cwd;
1034 const existing = sessions.get(input.threadId);
1035 if (existing) {
1036 yield* stopOpenCodeContext(existing);
1037 sessions.delete(input.threadId);
1038 }
1039
1040 const started = yield* Effect.gen(function* () {
1041 const sessionScope = yield* Scope.make();
1042 const startedExit = yield* Effect.exit(
1043 Effect.gen(function* () {
1044 // The runtime binds the server's lifetime to the Scope.Scope
1045 // we provide below — closing `sessionScope` kills the child
1046 // process automatically. No manual `server.close()` needed.
1047 const server = yield* openCodeRuntime.connectToOpenCodeServer({
1048 binaryPath,
1049 serverUrl,
1050 ...(options?.environment ? { environment: options.environment } : {}),
1051 });
1052 const client = openCodeRuntime.createOpenCodeSdkClient({
1053 baseUrl: server.url,
1054 directory,
1055 ...(server.external && serverPassword ? { serverPassword } : {}),
1056 });
1057 const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
1058 if (mcpSession && !server.external) {
1059 yield* runOpenCodeSdk("mcp.add", () =>
1060 client.mcp.add({
1061 name: "v12",
1062 config: {
1063 type: "remote",
1064 url: mcpSession.endpoint,
1065 headers: {
1066 Authorization: mcpSession.authorizationHeader,
1067 },
1068 oauth: false,
1069 },
1070 }),
1071 );
1072 }
1073 const openCodeSession = yield* runOpenCodeSdk("session.create", () =>
1074 client.session.create({
1075 title: `V12 ${input.threadId}`,
1076 permission: buildOpenCodePermissionRules(input.runtimeMode),
1077 }),
1078 );
1079 if (!openCodeSession.data) {
1080 return yield* new OpenCodeRuntimeError({
1081 operation: "session.create",
1082 detail: "OpenCode session.create returned no session payload.",
1083 });
1084 }
1085 return {
1086 sessionScope,
1087 server,
1088 client,
1089 openCodeSession: openCodeSession.data,
1090 };
1091 }).pipe(Effect.provideService(Scope.Scope, sessionScope)),
1092 );
1093 if (Exit.isFailure(startedExit)) {
1094 yield* Scope.close(sessionScope, Exit.void).pipe(Effect.ignore);
1095 return yield* toProcessError(input.threadId, Cause.squash(startedExit.cause));
1096 }
1097 return startedExit.value;
1098 });
1099
1100 // Guard against a concurrent startSession call that may have raced
1101 // and already inserted a session while we were awaiting async work.
1102 const raceWinner = sessions.get(input.threadId);
1103 if (raceWinner) {
1104 // Another call won the race – clean up the session we just created
1105 // (including the remote SDK session) and return the existing one.
1106 yield* runOpenCodeSdk("session.abort", () =>
1107 started.client.session.abort({
1108 sessionID: started.openCodeSession.id,
1109 }),
1110 ).pipe(Effect.ignore);
1111 yield* Scope.close(started.sessionScope, Exit.void).pipe(Effect.ignore);
1112 return raceWinner.session;
1113 }
1114
1115 const createdAt = yield* nowIso;
1116 const session: ProviderSession = {
1117 provider: PROVIDER,
1118 providerInstanceId: boundInstanceId,
1119 status: "ready",
1120 runtimeMode: input.runtimeMode,
1121 cwd: directory,
1122 ...(input.modelSelection ? { model: input.modelSelection.model } : {}),
1123 threadId: input.threadId,
1124 createdAt,
1125 updatedAt: createdAt,
1126 };
1127
1128 const context: OpenCodeSessionContext = {
1129 session,
1130 client: started.client,
1131 server: started.server,
1132 directory,
1133 openCodeSessionId: started.openCodeSession.id,
1134 pendingPermissions: new Map(),
1135 pendingQuestions: new Map(),
1136 partById: new Map(),
1137 emittedTextByPartId: new Map(),
1138 messageRoleById: new Map(),
1139 completedAssistantPartIds: new Set(),
1140 turns: [],
1141 activeTurnId: undefined,
1142 activeAgent: undefined,
1143 activeVariant: undefined,
1144 stopped: yield* Ref.make(false),
1145 sessionScope: started.sessionScope,
1146 };
1147 sessions.set(input.threadId, context);
1148 yield* startEventPump(context);
1149
1150 yield* emit({
1151 ...(yield* buildEventBase({ threadId: input.threadId })),
1152 type: "session.started",
1153 payload: {
1154 message: "OpenCode session started",
1155 },
1156 });
1157 yield* emit({
1158 ...(yield* buildEventBase({ threadId: input.threadId })),
1159 type: "thread.started",
1160 payload: {
1161 providerThreadId: started.openCodeSession.id,
1162 },
1163 });
1164
1165 return session;
1166 },
1167 );
1168
1169 const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
1170 const context = ensureSessionContext(sessions, input.threadId);
1171 // A sendTurn while a turn is active is a steer: OpenCode queues the
1172 // prompt into the busy session and the work continues as one turn, so
1173 // the active turn id is reused instead of opening a new turn.
1174 const steeringTurnId = context.activeTurnId;
1175 const turnId = steeringTurnId ?? TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
1176 const modelSelection =
1177 input.modelSelection ??
1178 (context.session.model
1179 ? { instanceId: boundInstanceId, model: context.session.model }
1180 : undefined);
1181 if (modelSelection !== undefined && modelSelection.instanceId !== boundInstanceId) {
1182 return yield* new ProviderAdapterValidationError({
1183 provider: PROVIDER,
1184 operation: "sendTurn",
1185 issue: `OpenCode model selection is bound to instance '${modelSelection?.instanceId}', expected '${boundInstanceId}'.`,
1186 });
1187 }
1188 const parsedModel = parseOpenCodeModelSlug(modelSelection?.model);
1189 if (!parsedModel) {
1190 return yield* new ProviderAdapterValidationError({
1191 provider: PROVIDER,
1192 operation: "sendTurn",
1193 issue: "OpenCode model selection must use the 'provider/model' format.",
1194 });
1195 }
1196
1197 const text = input.input?.trim();
1198 const fileParts = toOpenCodeFileParts({
1199 attachments: input.attachments,
1200 resolveAttachmentPath: (attachment) =>
1201 resolveAttachmentPath({
1202 attachmentsDir: serverConfig.attachmentsDir,
1203 attachment,
1204 }),
1205 });
1206 if ((!text || text.length === 0) && fileParts.length === 0) {
1207 return yield* new ProviderAdapterValidationError({
1208 provider: PROVIDER,
1209 operation: "sendTurn",
1210 issue: "OpenCode turns require text input or at least one attachment.",
1211 });
1212 }
1213
1214 const agent = getModelSelectionStringOptionValue(modelSelection, "agent");
1215 const variant = getModelSelectionStringOptionValue(modelSelection, "variant");
1216
1217 context.activeTurnId = turnId;
1218 context.activeAgent = agent ?? (input.interactionMode === "plan" ? "plan" : undefined);
1219 context.activeVariant = variant;
1220 yield* updateProviderSession(
1221 context,
1222 {
1223 status: "running",
1224 activeTurnId: turnId,
1225 model: modelSelection?.model ?? context.session.model,
1226 },
1227 { clearLastError: true },
1228 );
1229
1230 if (steeringTurnId === undefined) {
1231 yield* emit({
1232 ...(yield* buildEventBase({ threadId: input.threadId, turnId })),
1233 type: "turn.started",
1234 payload: {
1235 model: modelSelection?.model ?? context.session.model,
1236 ...(variant ? { effort: variant } : {}),
1237 },
1238 });
1239 }
1240
1241 yield* runOpenCodeSdk("session.promptAsync", () =>
1242 context.client.session.promptAsync({
1243 sessionID: context.openCodeSessionId,
1244 model: parsedModel,
1245 ...(context.activeAgent ? { agent: context.activeAgent } : {}),
1246 ...(context.activeVariant ? { variant: context.activeVariant } : {}),
1247 parts: [...(text ? [{ type: "text" as const, text }] : []), ...fileParts],
1248 }),
1249 ).pipe(
1250 Effect.mapError(toRequestError),
1251 // On failure of a fresh turn: clear active-turn state, flip the
1252 // session back to ready with lastError set, emit turn.aborted, then
1253 // let the typed error propagate. We don't need to rebuild the error
1254 // here — `toRequestError` already produced the right shape. A failed
1255 // steer leaves the still-running original turn untouched.
1256 Effect.tapError((requestError) =>
1257 steeringTurnId !== undefined
1258 ? Effect.void
1259 : Effect.gen(function* () {
1260 context.activeTurnId = undefined;
1261 context.activeAgent = undefined;
1262 context.activeVariant = undefined;
1263 yield* updateProviderSession(
1264 context,
1265 {
1266 status: "ready",
1267 model: modelSelection?.model ?? context.session.model,
1268 lastError: requestError.detail,
1269 },
1270 { clearActiveTurnId: true },
1271 );
1272 yield* emit({
1273 ...(yield* buildEventBase({
1274 threadId: input.threadId,
1275 turnId,
1276 })),
1277 type: "turn.aborted",
1278 payload: {
1279 reason: requestError.detail,
1280 },
1281 });
1282 }),
1283 ),
1284 );
1285
1286 return {
1287 threadId: input.threadId,
1288 turnId,
1289 };
1290 });
1291
1292 const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
1293 function* (threadId, turnId) {
1294 const context = ensureSessionContext(sessions, threadId);
1295 yield* runOpenCodeSdk("session.abort", () =>
1296 context.client.session.abort({ sessionID: context.openCodeSessionId }),
1297 ).pipe(Effect.mapError(toRequestError));
1298 if (turnId ?? context.activeTurnId) {
1299 yield* emit({
1300 ...(yield* buildEventBase({
1301 threadId,
1302 turnId: turnId ?? context.activeTurnId,
1303 })),
1304 type: "turn.aborted",
1305 payload: {
1306 reason: "Interrupted by user.",
1307 },
1308 });
1309 }
1310 },
1311 );
1312
1313 const respondToRequest: OpenCodeAdapterShape["respondToRequest"] = Effect.fn(
1314 "respondToRequest",
1315 )(function* (threadId, requestId, decision) {
1316 const context = ensureSessionContext(sessions, threadId);
1317 if (!context.pendingPermissions.has(requestId)) {
1318 return yield* new ProviderAdapterRequestError({
1319 provider: PROVIDER,
1320 method: "permission.reply",
1321 detail: `Unknown pending permission request: ${requestId}`,
1322 });
1323 }
1324
1325 yield* runOpenCodeSdk("permission.reply", () =>
1326 context.client.permission.reply({
1327 requestID: requestId,
1328 reply: toOpenCodePermissionReply(decision),
1329 }),
1330 ).pipe(Effect.mapError(toRequestError));
1331 });
1332
1333 const respondToUserInput: OpenCodeAdapterShape["respondToUserInput"] = Effect.fn(
1334 "respondToUserInput",
1335 )(function* (threadId, requestId, answers) {
1336 const context = ensureSessionContext(sessions, threadId);
1337 const request = context.pendingQuestions.get(requestId);
1338 if (!request) {
1339 return yield* new ProviderAdapterRequestError({
1340 provider: PROVIDER,
1341 method: "question.reply",
1342 detail: `Unknown pending user-input request: ${requestId}`,
1343 });
1344 }
1345
1346 yield* runOpenCodeSdk("question.reply", () =>
1347 context.client.question.reply({
1348 requestID: requestId,
1349 answers: toOpenCodeQuestionAnswers(request, answers),
1350 }),
1351 ).pipe(Effect.mapError(toRequestError));
1352 });
1353
1354 const stopSession: OpenCodeAdapterShape["stopSession"] = Effect.fn("stopSession")(
1355 function* (threadId) {
1356 const context = sessions.get(threadId);
1357 if (!context) {
1358 throw new ProviderAdapterSessionNotFoundError({
1359 provider: PROVIDER,
1360 threadId,
1361 });
1362 }
1363 const stopped = yield* stopOpenCodeContext(context);
1364 sessions.delete(threadId);
1365 if (!stopped) {
1366 return;
1367 }
1368 yield* emit({
1369 ...(yield* buildEventBase({ threadId })),
1370 type: "session.exited",
1371 payload: {
1372 reason: "Session stopped.",
1373 recoverable: false,
1374 exitKind: "graceful",
1375 },
1376 });
1377 },
1378 );
1379
1380 const listSessions: OpenCodeAdapterShape["listSessions"] = () =>
1381 Effect.sync(() => [...sessions.values()].map((context) => context.session));
1382
1383 const hasSession: OpenCodeAdapterShape["hasSession"] = (threadId) =>
1384 Effect.sync(() => sessions.has(threadId));
1385
1386 const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")(
1387 function* (threadId) {
1388 const context = ensureSessionContext(sessions, threadId);
1389 const messages = yield* runOpenCodeSdk("session.messages", () =>
1390 context.client.session.messages({
1391 sessionID: context.openCodeSessionId,
1392 }),
1393 ).pipe(Effect.mapError(toRequestError));
1394
1395 const turns: Array<OpenCodeTurnSnapshot> = [];
1396 for (const entry of messages.data ?? []) {
1397 if (entry.info.role === "assistant") {
1398 turns.push({
1399 id: TurnId.make(entry.info.id),
1400 items: [entry.info, ...entry.parts],
1401 });
1402 }
1403 }
1404
1405 return {
1406 threadId,
1407 turns,
1408 };
1409 },
1410 );
1411
1412 const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(
1413 function* (threadId, numTurns) {
1414 const context = ensureSessionContext(sessions, threadId);
1415 const messages = yield* runOpenCodeSdk("session.messages", () =>
1416 context.client.session.messages({
1417 sessionID: context.openCodeSessionId,
1418 }),
1419 ).pipe(Effect.mapError(toRequestError));
1420
1421 const assistantMessages = (messages.data ?? []).filter(
1422 (entry) => entry.info.role === "assistant",
1423 );
1424 const targetIndex = assistantMessages.length - numTurns - 1;
1425 const target = targetIndex >= 0 ? assistantMessages[targetIndex] : null;
1426 yield* runOpenCodeSdk("session.revert", () =>
1427 context.client.session.revert({
1428 sessionID: context.openCodeSessionId,
1429 ...(target ? { messageID: target.info.id } : {}),
1430 }),
1431 ).pipe(Effect.mapError(toRequestError));
1432
1433 return yield* readThread(threadId);
1434 },
1435 );
1436
1437 const stopAll: OpenCodeAdapterShape["stopAll"] = () =>
1438 Effect.gen(function* () {
1439 const contexts = [...sessions.values()];
1440 sessions.clear();
1441 // `stopOpenCodeContext` is typed as never-failing — SDK aborts are
1442 // already `Effect.ignore`'d inside it. `ignoreCause` here also
1443 // swallows defects from throwing finalizers so one bad close can't
1444 // interrupt the sibling fibers. Same pattern as the layer finalizer.
1445 yield* Effect.forEach(
1446 contexts,
1447 (context) => Effect.ignoreCause(stopOpenCodeContext(context)),
1448 { concurrency: "unbounded", discard: true },
1449 );
1450 });
1451
1452 return {
1453 provider: PROVIDER,
1454 capabilities: {
1455 sessionModelSwitch: "in-session",
1456 },
1457 startSession,
1458 sendTurn,
1459 interruptTurn,
1460 respondToRequest,
1461 respondToUserInput,
1462 stopSession,
1463 listSessions,
1464 hasSession,
1465 readThread,
1466 rollbackThread,
1467 stopAll,
1468 get streamEvents() {
1469 return Stream.fromQueue(runtimeEvents);
1470 },
1471 } satisfies OpenCodeAdapterShape;
1472 });
1473}