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