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