1721 lines · 59.8 KB · TypeScript
RawDownload
import {  EventId,  type OpenCodeSettings,  ProviderDriverKind,  ProviderInstanceId,  type ProviderRuntimeEvent,  type ProviderSession,  RuntimeItemId,  RuntimeRequestId,  ThreadId,  type ToolLifecycleItemType,  TurnId,  type UserInputQuestion,} from "@t3tools/contracts";import * as Cause from "effect/Cause";import * as Crypto from "effect/Crypto";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Exit from "effect/Exit";import * as FileSystem from "effect/FileSystem";import * as Path from "effect/Path";import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";import * as Scope from "effect/Scope";import * as Stream from "effect/Stream";import type { OpencodeClient, Part, PermissionRequest, QuestionRequest } from "@opencode-ai/sdk/v2";import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { resolveAttachmentPath } from "../../attachmentStore.ts";import { ServerConfig } from "../../config.ts";import * as McpProviderSession from "../../mcp/McpProviderSession.ts";import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";import {  ProviderAdapterProcessError,  ProviderAdapterRequestError,  ProviderAdapterSessionClosedError,  ProviderAdapterSessionNotFoundError,  ProviderAdapterValidationError,} from "../Errors.ts";import { type OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";import {  buildOpenCodePermissionRules,  OpenCodeRuntime,  OpenCodeRuntimeError,  openCodeQuestionId,  openCodeRuntimeErrorDetail,  parseOpenCodeModelSlug,  runOpenCodeSdk,  toOpenCodeFileParts,  toOpenCodePermissionReply,  toOpenCodeQuestionAnswers,  type OpenCodeServerConnection,} from "../opencodeRuntime.ts";import * as Option from "effect/Option"; const PROVIDER = ProviderDriverKind.make("opencode"); /** * Version tag stamped into the OpenCode resume cursor. Bump if the cursor * shape changes so stale-shaped cursors written by older builds are ignored * rather than misread (mirrors GROK_RESUME_VERSION / CURSOR_RESUME_VERSION). */const OPENCODE_RESUME_VERSION = 1 as const; /** * Decode a persisted resume cursor into the upstream `ses_…` id. Anything * that isn't a current-version cursor with a non-empty id means "no resume" * rather than an error. Re-adopting the session id IS the resume mechanism — * OpenCode scopes a conversation's history by session id. */function parseOpenCodeResume(raw: unknown): { readonly sessionId: string } | undefined {  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {    return undefined;  }  const record = raw as Record<string, unknown>;  if (record.schemaVersion !== OPENCODE_RESUME_VERSION) {    return undefined;  }  if (typeof record.sessionId !== "string" || record.sessionId.trim().length === 0) {    return undefined;  }  return { sessionId: record.sessionId.trim() };} /** * Whether an error definitively reports a missing session. Only a confirmed * miss may silently start a fresh session; any other failure (the SDK client * is `throwOnError: true`, so `session.get` rejects on every non-2xx) must * propagate, or a transient blip resets a live thread to an empty one — the * #3604 silent context loss. Decides on structured signals only, never free * text: a numeric 404 or the exact `NotFoundError` name, found via a bounded walk * over `cause`/`body`/`error`/`data`. An explicit non-404 status seals its * subtree so a wrapped "NotFound" name can't reclassify a real failure. * Exported for unit testing. */export function isOpenCodeNotFound(cause: unknown): boolean {  const seen = new Set<unknown>();  const queue: Array<unknown> = [cause];  for (let steps = 0; queue.length > 0 && steps < 32; steps += 1) {    const node = queue.shift();    if (node === null || typeof node !== "object" || seen.has(node)) {      continue;    }    seen.add(node);    const record = node as Record<string, unknown>;     const response = record.response;    const statuses = [      record.status,      record.statusCode,      response !== null && typeof response === "object"        ? (response as { readonly status?: unknown }).status        : undefined,    ].filter((status): status is number => typeof status === "number");    if (statuses.includes(404)) {      return true;    }    if (statuses.length > 0) {      continue;    }     const name = record.name;    if (typeof name === "string" && name.toLowerCase() === "notfounderror") {      return true;    }     for (const key of ["cause", "body", "error", "data"] as const) {      if (record[key] !== undefined) {        queue.push(record[key]);      }    }  }  return false;} /** * Whether two directory spellings name the same location. Raw string * equality misreads a trailing slash, `.`/`..` segment, or symlinked cwd * (macOS `/tmp` → `/private/tmp`) as a cwd change, needlessly forking the * session on every resume. Lexically equal paths short-circuit; otherwise * both sides go through `realPath`, each falling back to its lexical form * on failure (deleted directory, external-server path) — so the probe can * only widen matches, never split them. Takes the services as arguments so * adapter methods stay service-free. Exported for unit testing. */export function isSameOpenCodeDirectory(  fileSystem: FileSystem.FileSystem,  path: Path.Path,  left: string,  right: string,): Effect.Effect<boolean> {  const lexicalLeft = path.resolve(left);  const lexicalRight = path.resolve(right);  if (lexicalLeft === lexicalRight) {    return Effect.succeed(true);  }  const canonicalize = (lexical: string) =>    fileSystem.realPath(lexical).pipe(Effect.orElseSucceed(() => lexical));  return Effect.zipWith(    canonicalize(lexicalLeft),    canonicalize(lexicalRight),    (canonicalLeft, canonicalRight) => canonicalLeft === canonicalRight,  );} interface OpenCodeTurnSnapshot {  readonly id: TurnId;  readonly items: Array<unknown>;} type OpenCodeSubscribedEvent =  Awaited<ReturnType<OpencodeClient["event"]["subscribe"]>> extends {    readonly stream: AsyncIterable<infer TEvent>;  }    ? TEvent    : never; function trimText(value: string | undefined | null): string | undefined {  const trimmed = value?.trim();  return trimmed && trimmed.length > 0 ? trimmed : undefined;} function openCodeEventSessionId(event: OpenCodeSubscribedEvent): string | undefined {  const properties = "properties" in event ? event.properties : undefined;  if (!properties || typeof properties !== "object") {    return undefined;  }   const sessionID = (properties as { readonly sessionID?: unknown }).sessionID;  const sessionIDFromProperties = typeof sessionID === "string" ? sessionID : undefined;  if (sessionIDFromProperties) {    return sessionIDFromProperties;  }   const info = (properties as { readonly info?: { readonly id?: unknown } }).info;  return info && typeof info.id === "string" ? info.id : undefined;} function openCodeEventSessionTitle(event: OpenCodeSubscribedEvent): string | undefined {  if (event.type !== "session.updated") {    return undefined;  }   return trimText(event.properties.info.title);} interface OpenCodeSessionContext {  session: ProviderSession;  readonly client: OpencodeClient;  readonly server: OpenCodeServerConnection;  readonly directory: string;  readonly openCodeSessionId: string;  readonly pendingPermissions: Map<string, PermissionRequest>;  readonly pendingQuestions: Map<string, QuestionRequest>;  readonly messageRoleById: Map<string, "user" | "assistant">;  readonly partById: Map<string, Part>;  readonly emittedTextByPartId: Map<string, string>;  readonly completedAssistantPartIds: Set<string>;  readonly turns: Array<OpenCodeTurnSnapshot>;  activeTurnId: TurnId | undefined;  activeAgent: string | undefined;  activeVariant: string | undefined;  /**   * One-shot guard flipped by `stopOpenCodeContext` / `emitUnexpectedExit`.   * The session lifecycle is owned by `sessionScope`; this Ref exists only   * so concurrent callers can race the transition safely via `getAndSet`.   */  readonly stopped: Ref.Ref<boolean>;  /**   * Sole lifecycle handle for the session. Closing this scope:   *   - aborts the `AbortController` registered as a finalizer   *     (cancels the in-flight `event.subscribe` fetch),   *   - interrupts the event-pump and server-exit fibers forked   *     via `Effect.forkIn(sessionScope)`,   *   - tears down the OpenCode server process for scope-owned servers.   */  readonly sessionScope: Scope.Closeable;} export interface OpenCodeAdapterLiveOptions {  readonly instanceId?: ProviderInstanceId;  readonly environment?: NodeJS.ProcessEnv;  readonly nativeEventLogPath?: string;  readonly nativeEventLogger?: EventNdjsonLogger;} const nowIso = Effect.map(DateTime.now, DateTime.formatIso); /** * Map a tagged OpenCodeRuntimeError produced by {@link runOpenCodeSdk} into * the adapter-boundary `ProviderAdapterRequestError`. SDK-method-level call * sites pipe through this in `Effect.mapError` so they never build the error * shape by hand. */const toRequestError = (cause: OpenCodeRuntimeError): ProviderAdapterRequestError =>  new ProviderAdapterRequestError({    provider: PROVIDER,    method: cause.operation,    detail: cause.detail,    cause: cause.cause,  }); /** * Map a `Cause.squash`-ed failure into a `ProviderAdapterProcessError`. The * typed cause is usually an `OpenCodeRuntimeError` (from {@link runOpenCodeSdk}), * in which case we preserve its `detail`; otherwise we fall back to * {@link openCodeRuntimeErrorDetail} for unknown causes (defects, etc.). */const toProcessError = (threadId: ThreadId, cause: unknown): ProviderAdapterProcessError =>  new ProviderAdapterProcessError({    provider: PROVIDER,    threadId,    detail: OpenCodeRuntimeError.is(cause) ? cause.detail : openCodeRuntimeErrorDetail(cause),    cause,  }); type EventBaseInput = {  readonly threadId: ThreadId;  readonly turnId?: TurnId | undefined;  readonly itemId?: string | undefined;  readonly requestId?: string | undefined;  readonly createdAt?: string | undefined;  readonly raw?: unknown;}; function toToolLifecycleItemType(toolName: string): ToolLifecycleItemType {  const normalized = toolName.toLowerCase();  if (normalized.includes("bash") || normalized.includes("command")) {    return "command_execution";  }  if (    normalized.includes("edit") ||    normalized.includes("write") ||    normalized.includes("patch") ||    normalized.includes("multiedit")  ) {    return "file_change";  }  if (normalized.includes("web")) {    return "web_search";  }  if (normalized.includes("mcp")) {    return "mcp_tool_call";  }  if (normalized.includes("image")) {    return "image_view";  }  if (    normalized.includes("task") ||    normalized.includes("agent") ||    normalized.includes("subtask")  ) {    return "collab_agent_tool_call";  }  return "dynamic_tool_call";} function mapPermissionToRequestType(  permission: string,): "command_execution_approval" | "file_read_approval" | "file_change_approval" | "unknown" {  switch (permission) {    case "bash":      return "command_execution_approval";    case "read":      return "file_read_approval";    case "edit":      return "file_change_approval";    default:      return "unknown";  }} function mapPermissionDecision(reply: "once" | "always" | "reject"): string {  switch (reply) {    case "once":      return "accept";    case "always":      return "acceptForSession";    case "reject":    default:      return "decline";  }} function resolveTurnSnapshot(  context: OpenCodeSessionContext,  turnId: TurnId,): OpenCodeTurnSnapshot {  const existing = context.turns.find((turn) => turn.id === turnId);  if (existing) {    return existing;  }   const created: OpenCodeTurnSnapshot = { id: turnId, items: [] };  context.turns.push(created);  return created;} function appendTurnItem(  context: OpenCodeSessionContext,  turnId: TurnId | undefined,  item: unknown,): void {  if (!turnId) {    return;  }  resolveTurnSnapshot(context, turnId).items.push(item);} const ensureSessionContext = Effect.fn("ensureSessionContext")(function* (  sessions: ReadonlyMap<ThreadId, OpenCodeSessionContext>,  threadId: ThreadId,) {  const session = sessions.get(threadId);  if (!session) {    return yield* new ProviderAdapterSessionNotFoundError({      provider: PROVIDER,      threadId,    });  }  if (yield* Ref.get(session.stopped)) {    return yield* new ProviderAdapterSessionClosedError({      provider: PROVIDER,      threadId,    });  }  return session;}); function normalizeQuestionRequest(request: QuestionRequest): ReadonlyArray<UserInputQuestion> {  return request.questions.map((question, index) => ({    id: openCodeQuestionId(index, question),    header: question.header,    question: question.question,    options: question.options.map((option) => ({      label: option.label,      description: option.description,    })),    ...(question.multiple ? { multiSelect: true } : {}),  }));} function resolveTextStreamKind(part: Part | undefined): "assistant_text" | "reasoning_text" {  return part?.type === "reasoning" ? "reasoning_text" : "assistant_text";} function textFromPart(part: Part): string | undefined {  switch (part.type) {    case "text":    case "reasoning":      return part.text;    default:      return undefined;  }} function commonPrefixLength(left: string, right: string): number {  let index = 0;  while (index < left.length && index < right.length && left[index] === right[index]) {    index += 1;  }  return index;} function resolveLatestAssistantText(previousText: string | undefined, nextText: string): string {  if (previousText && previousText.length > nextText.length && previousText.startsWith(nextText)) {    return previousText;  }  return nextText;} export function mergeOpenCodeAssistantText(  previousText: string | undefined,  nextText: string,): {  readonly latestText: string;  readonly deltaToEmit: string;} {  const latestText = resolveLatestAssistantText(previousText, nextText);  return {    latestText,    deltaToEmit: latestText.slice(commonPrefixLength(previousText ?? "", latestText)),  };} export function appendOpenCodeAssistantTextDelta(  previousText: string,  delta: string,): {  readonly nextText: string;  readonly deltaToEmit: string;} {  return {    nextText: previousText + delta,    deltaToEmit: delta,  };} const isoFromEpochMs = (value: number) =>  DateTime.make(value).pipe(    Option.match({      onNone: () => undefined,      onSome: DateTime.formatIso,    }),  ); function messageRoleForPart(  context: OpenCodeSessionContext,  part: Pick<Part, "messageID" | "type">,): "assistant" | "user" | undefined {  const known = context.messageRoleById.get(part.messageID);  if (known) {    return known;  }  return part.type === "tool" ? "assistant" : undefined;} function detailFromToolPart(part: Extract<Part, { type: "tool" }>): string | undefined {  switch (part.state.status) {    case "completed":      return part.state.output;    case "error":      return part.state.error;    case "running":      return part.state.title;    default:      return undefined;  }} function toolStateCreatedAt(part: Extract<Part, { type: "tool" }>): string | undefined {  switch (part.state.status) {    case "running":      return isoFromEpochMs(part.state.time.start);    case "completed":    case "error":      return isoFromEpochMs(part.state.time.end);    default:      return undefined;  }

Lines 1–500 of 1721.