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