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