sailfork / t3code-github / packages/ provider-muse/ src/ server/ adapter.ts

import { MspError, type ProcessExit, type SendUserTurnOptions } from "@muse-code/sdk";
import {
  MUSE_DEFAULT_MODEL,
  ProviderDriverKind,
  type ModelSelection,
  type OrchestrationV2AppThread,
  type OrchestrationV2ConversationMessage,
  type OrchestrationV2ExecutionNode,
  type OrchestrationV2ProviderCapabilities,
  type OrchestrationV2ProviderSession,
  type OrchestrationV2ProviderThread,
  type OrchestrationV2ProviderTurn,
  type OrchestrationV2RuntimeRequest,
  type OrchestrationV2Subagent,
  type OrchestrationV2TurnItemStatus,
  type NodeId,
  type OrchestrationV2TurnItem,
  type ProviderInstanceId,
  type PlanId,
  type OrchestrationV2PlanStep,
  type ProviderApprovalDecision,
  type RuntimeRequestId,
  type ServerProviderModel,
  type ThreadId,
} from "@t3tools/contracts";
import type { MuseSettings } from "../settings.ts";
import { AgentScope } from "@t3tools/shared/AgentScope";
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";

import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import { museModelCapabilities, resolveMuseReasoningEffort } from "./modelCatalog.ts";
import {
  MuseApproval,
  MuseCompactResult,
  MuseContextUsage,
  MuseDelta,
  MuseItemEvent,
  MuseSessionResult,
  MuseSubscriptionUsage,
  MuseTokenUsageEvent,
  MuseTodoList,
  MuseTurnRetryScheduled,
  MuseTurnCompleted,
  MuseTurnStartResult,
  MuseUserInput,
  museApprovalChoices,
  museApprovalDecision,
  museApprovalOptions,
  type MuseItem,
} from "./protocol.ts";
import { isMuseUsageLimitFailure, museUsageLimitResetAt } from "./usageLimits.ts";
import {
  createMuseSdkHostEffect,
  MuseSdkError,
  museApprovalMode,
  museCanonicalPath,
  musePermissionProfile,
  museWorkspaceRoot,
  type createMuseSdkHost,
  type MuseSdkHost,
} from "./sdk.ts";
import type * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import {
  providerMessageTextWithAttachmentPaths,
  isProviderNativeImageAttachment,
} from "@t3tools/provider-core/server/attachmentPrompt";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import {
  backgroundWorkNotification,
  type BackgroundWorkReport,
} from "@t3tools/provider-core/server/notification";
import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import { makeProviderFailure } from "@t3tools/provider-core/server/failure";
import {
  makeSubagentChildThread,
  makeSubagentConversationArtifacts,
  subagentThreadTitle,
} from "@t3tools/provider-core/server/subagentProjection";
import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
import { museItemStatus, museToolPresentation } from "./itemPresentation.ts";

const MUSE_PROVIDER = ProviderDriverKind.make("muse");
const isOpenSessionError = Schema.is(ProviderAdapter.ProviderAdapterOpenSessionError);
const isProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError);

const MuseProviderCapabilitiesV2 = {
  runtimePolicy: { enforcement: "native" },
  sessions: {
    supportsMultipleProviderThreadsPerSession: false,
    supportsModelSwitchInSession: true,
    supportsProviderSwitchingViaHandoff: true,
    supportsRuntimeModeSwitchInSession: false,
    pendingRequestsSurviveRestart: false,
  },
  threads: {
    canCreateEmptyThread: true,
    canReadThreadSnapshot: true,
    canRollbackThread: false,
    canForkThread: false,
    canForkFromTurn: false,
    canForkFromSubagentThread: false,
    exposesNativeThreadId: true,
  },
  turns: {
    exposesNativeTurnId: true,
    emitsTurnStarted: true,
    emitsTurnCompleted: true,
    supportsInterrupt: true,
    supportsActiveSteering: true,
    supportsSteeringByInterruptRestart: false,
    supportsQueuedMessages: true,
    terminalStatusQuality: "strong",
  },
  streaming: {
    streamsAssistantText: true,
    streamsReasoning: true,
    streamsToolOutput: true,
    streamsPlanText: false,
    emitsMessageCompleted: true,
  },
  tools: {
    exposesToolItemIds: true,
    emitsToolStarted: true,
    emitsToolCompleted: true,
    emitsToolOutput: true,
    supportsMcpTools: true,
    supportsDynamicToolCallbacks: false,
  },
  approvals: {
    supportsCommandApproval: true,
    supportsFileReadApproval: true,
    supportsFileChangeApproval: true,
    supportsApplyPatchApproval: false,
    approvalsHaveNativeRequestIds: true,
    approvalCallbacksAreLiveOnly: true,
    approvalsCanOriginateFromSubagents: true,
  },
  planning: {
    emitsPlanUpdated: true,
    emitsTodoList: true,
    emitsProposedPlan: false,
    supportsStructuredQuestions: true,
    planDeltasHaveItemIds: false,
  },
  subagents: {
    supportsSubagents: true,
    exposesSubagentThreadIds: false,
    emitsSubagentLifecycle: true,
    canWaitForSubagents: false,
    canCloseSubagents: false,
    canForkSubagentThread: false,
  },
  context: {
    acceptsSystemContext: false,
    acceptsDeveloperContext: false,
    acceptsSyntheticUserContext: true,
    canGenerateSummaries: false,
    canConsumeHandoffSummaries: true,
    supportsDeltaHandoff: true,
    supportsFullThreadHandoff: true,
    maxRecommendedHandoffChars: null,
  },
  checkpointing: {
    appCanCheckpointFilesystem: true,
    supportsNestedCheckpointScopes: false,
    providerCanRollbackConversation: false,
    providerRollbackReturnsSnapshot: false,
    providerCanReadConversationSnapshot: true,
  },
  identity: {
    nativeThreadIds: "strong",
    nativeTurnIds: "strong",
    nativeItemIds: "strong",
    nativeRequestIds: "strong",
  },
} satisfies OrchestrationV2ProviderCapabilities;

export interface MuseAdapterV2Options {
  readonly instanceId: ProviderInstanceId;
  readonly settings: MuseSettings;
  readonly environment: NodeJS.ProcessEnv;
  readonly modelCatalog?: Effect.Effect<ReadonlyArray<ServerProviderModel>>;
  readonly createHost?: typeof createMuseSdkHost;
  readonly requestTimeoutMs?: number;
  readonly nativeEventLogger?: ProviderEventLoggers.EventNdjsonLogger;
  readonly continuationRequests?: {
    readonly offer: (
      request: ProviderContinuationRequests.ProviderContinuationRequest,
    ) => Effect.Effect<void>;
  };
}

interface ActiveTurn {
  readonly input: ProviderAdapter.ProviderAdapterV2TurnInput;
  providerTurn: OrchestrationV2ProviderTurn;
  readonly nativeId: string;
  readonly joined: Set<string>;
  readonly items: Map<string, MuseItem>;
  readonly ordinals: Map<string, number>;
  readonly started: Map<string, DateTime.Utc>;
  readonly dirty: Set<string>;
  readonly settledRequests: Set<string>;
  readonly done: Deferred.Deferred<void>;
  todoPlanId?: PlanId;
  nextOrdinal: number;
  flushScheduled: boolean;
  interruptRequested: boolean;
  compact: boolean;
}

interface PendingRequest {
  readonly native:
    | { type: "approval"; value: MuseApproval }
    | { type: "question"; value: MuseUserInput };
  request: OrchestrationV2RuntimeRequest;
  node: OrchestrationV2ExecutionNode;
  item: OrchestrationV2TurnItem;
  response?: Pick<OrchestrationV2RuntimeRequest, "decision" | "answers">;
  shown: boolean;
}

// Muse 1.4.4 cannot read/subscribe to inline child sessions; retain prompt, root status, and result here.
interface ChildContext {
  readonly childSessionId: string;
  readonly childThreadId: ThreadId;
  readonly appThread: OrchestrationV2AppThread;
  readonly rootNodeId: NodeId;
  readonly parentThreadId: ThreadId;
  status: OrchestrationV2TurnItemStatus;
  result?: string;
}

const nativeRef = (nativeId: string) => ({
  driver: MUSE_PROVIDER,
  nativeId,
  strength: "strong" as const,
});
/** The roster lists a child under its turn item's native id, so readers can pair the two. */
const backgroundTaskId = (item: MuseItem) =>
  item.kind === "subagent" ? item.childSessionId || item.subagentId || item.itemId : item.itemId;
const recordSchema = Schema.Record(Schema.String, Schema.Unknown);
const INFORMATIONAL_NOTIFICATIONS = new Set([
  "session/contextUsage",
  "session/tokenUsage",
  "session/todoListChanged",
  "turn/retryScheduled",
  "usage/changed",
]);
const TOOLS_WITH_NATIVE_ROWS = new Set(["write_todos", "request_user_input", "workflow"]);
const responseAnswerSchema = Schema.Union([Schema.String, Schema.Array(Schema.String)]);

export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* (
  options: MuseAdapterV2Options,
) {
  const idAllocator = yield* IdAllocator.IdAllocatorV2;
  const providerHost = yield* ProviderHost.ProviderHost;
  const fileSystem = yield* FileSystem.FileSystem;
  const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
  const agentScope = yield* AgentScope;

  const protocolError = (detail: string, payload?: unknown) =>
    new ProviderAdapter.ProviderAdapterProtocolError({
      driver: MUSE_PROVIDER,
      detail,
      ...(payload === undefined ? {} : { payload }),
    });
  return ProviderAdapter.ProviderAdapterV2.of({
    instanceId: options.instanceId,
    driver: MUSE_PROVIDER,
    getCapabilities: Effect.fn("MuseAdapter.getCapabilities")(function () {
      return Effect.succeed(MuseProviderCapabilitiesV2);
    }),
    planSelectionTransition: Effect.fn("MuseAdapter.planSelectionTransition")(function () {
      return Effect.succeed(turnScopedSelectionTransition());
    }),
    openSession: Effect.fn("MuseAdapterV2.openSession")(function* (
      input: ProviderAdapter.ProviderAdapterV2OpenSessionInput,
    ) {
      if (!options.settings.enabled) return yield* protocolError("Muse Code is disabled");
      if (input.runtimePolicy.interactionMode === "plan")
        return yield* protocolError("Muse Code does not support dedicated Plan mode");
      const scope = yield* Effect.scope;
      // Native realpath also corrects filesystem case, which Muse validates.
      const requestedCwd = input.runtimePolicy.cwd ?? providerHost.paths.cwd;
      const cwd = yield* museCanonicalPath(requestedCwd);
      const workspaceRoot = yield* museWorkspaceRoot(cwd);
      const now = yield* DateTime.now;
      let session: OrchestrationV2ProviderSession = {
        id: input.providerSessionId,
        driver: MUSE_PROVIDER,
        providerInstanceId: options.instanceId,
        status: "ready",
        cwd,
        model: input.modelSelection.model,
        capabilities: MuseProviderCapabilitiesV2,
        createdAt: now,
        updatedAt: now,
        lastError: null,
      };
      const events = yield* Queue.unbounded<
        ProviderAdapter.ProviderAdapterV2Event,
        ProviderAdapter.ProviderAdapterV2Error | Cause.Done
      >();
      type Inbox =
        | { type: "notification"; method: string; params: unknown; epoch: number }
        | { type: "failure"; cause: unknown; epoch: number }
        | { type: "flush"; turn: ActiveTurn };
      const inbox = yield* Queue.unbounded<Inbox>();
      const commands = yield* Semaphore.make(1);
      const eventPermit = yield* Semaphore.make(1);
      let host: MuseSdkHost;
      let hostEpoch = 0;
      let closed = false;
      let broken = false;
      // Only idle host failures can be retried on this runtime.
      let relaunchable = false;
      let nativeSessionId: string | undefined;
      let thread: OrchestrationV2ProviderThread | undefined;
      let active: ActiveTurn | undefined;
      let lastProviderTurn: OrchestrationV2ProviderTurn | undefined;
      let latestSubscriptionUsage: MuseSubscriptionUsage | undefined;
      const agentEndedAt = new Map<string, DateTime.Utc>();
      const resolveModel = Effect.fnUntraced(function* (selection: ModelSelection) {
        if (selection.model !== MUSE_DEFAULT_MODEL) return selection.model;
        const catalog = options.modelCatalog ? yield* options.modelCatalog : [];
        return catalog.find((model) => model.isDefault && !model.isCustom)?.slug;
      });
      const pending = new Map<RuntimeRequestId, PendingRequest>();
      const seenTerminals = new Set<string>();
      const observedChildren = new Map<string, ActiveTurn>();
      const childrenByItemId = new Map<string, ChildContext>();
      const agentTitles = new Map<string, string>();
      const finishedBackground: Array<BackgroundWorkReport> = [];
      let wake:
        | { readonly nativeId: string; readonly events: Array<[string, unknown]> }
        | undefined;
      const emit = (event: ProviderAdapter.ProviderAdapterV2Event) =>
        Queue.offer(events, event).pipe(Effect.asVoid);
      const decode = <A, I>(schema: Schema.Codec<A, I>, data: unknown) =>
        Schema.decodeUnknownEffect(schema)(data).pipe(
          Effect.mapError((cause) => protocolError("Invalid Muse protocol response", cause)),
        );
      const request = (
        method: string,
        params: Record<string, unknown>,
        command = true,
        commandId?: string,
      ) =>
        Effect.tryPromise({
          try: () =>
            command
              ? host.connection.command(
                  method,
                  { ...(nativeSessionId ? { sessionId: nativeSessionId } : {}), ...params },
                  {
                    ...(method === "turn/start" ? {} : { maxAttempts: 1 }),
                    ...(commandId ? { commandId } : {}),
                  },
                )
              : host.connection.request(method, {
                  ...(nativeSessionId ? { sessionId: nativeSessionId } : {}),
                  ...params,
                }),
          catch: (cause) =>
            protocolError(
              cause instanceof Error && cause.message
                ? `Muse ${method} failed: ${cause.message}`
                : `Muse ${method} failed`,
              cause,
            ),
        }).pipe(
          Effect.timeout(options.requestTimeoutMs ?? 30_000),
          Effect.catchTags({
            // The enclosing operation owns the span for this inline handler.
            TimeoutError: Effect.fnUntraced(function* (cause) {
              yield* eventPermit.withPermits(1)(failHost(cause));
              return yield* protocolError(`Muse ${method} timed out; its host was closed`, cause);
            }),
          }),
        );
      const updateSession = Effect.fnUntraced(function* (
        status: OrchestrationV2ProviderSession["status"],
        lastError: string | null = null,
      ) {
        session = {
          ...session,
          status,
          // lastError is the thread banner, so it gets the failure item's bounded, redacted text.
          lastError:
            lastError === null ? null : makeProviderFailure({ message: lastError }).message,
          updatedAt: yield* DateTime.now,
        };
        yield* emit({
          type: "provider_session.updated",
          driver: MUSE_PROVIDER,
          providerSession: session,
        });
      });
      const updateThread = Effect.fnUntraced(function* (
        patch: Partial<OrchestrationV2ProviderThread>,
      ) {
        if (!thread) return;
        thread = { ...thread, ...patch, updatedAt: yield* DateTime.now };
        yield* emit({
          type: "provider_thread.updated",
          driver: MUSE_PROVIDER,
          providerThread: thread,
        });
      });
      const itemIdentity = (turn: ActiveTurn, nativeId: string) =>
        `${options.instanceId}:${turn.input.providerThread.id}:${turn.nativeId}:${nativeId}`;
      const baseItem = (turn: ActiveTurn, nativeId: string, time: DateTime.Utc) => {
        if (!turn.ordinals.has(nativeId)) turn.ordinals.set(nativeId, turn.nextOrdinal++);
        if (!turn.started.has(nativeId)) turn.started.set(nativeId, time);
        const identity = itemIdentity(turn, nativeId);
        return {
          id: idAllocator.derive.turnItemFromProviderItem({
            driver: MUSE_PROVIDER,
            nativeItemId: identity,
          }),
          nodeId: idAllocator.derive.nodeFromProviderItem({
            driver: MUSE_PROVIDER,
            nativeItemId: identity,
          }),
          threadId: turn.input.threadId,
          runId: turn.input.runId,
          providerThreadId: turn.input.providerThread.id,
          providerTurnId: turn.providerTurn.id,
          nativeItemRef: nativeRef(nativeId),
          parentItemId: null,
          ordinal: turn.ordinals.get(nativeId)!,
          startedAt: turn.started.get(nativeId)!,
          updatedAt: time,
        };
      };
      const childItemIdentity = (context: ChildContext, nativeId: string) =>
        `${options.instanceId}:child:${context.childSessionId}:${nativeId}`;
      const itemStatus = (item: MuseItem): OrchestrationV2TurnItemStatus => {
        const status = museItemStatus(item);
        return status === "running" &&
          item.kind === "subagent" &&
          item.controlStatus === "resultReady"
          ? "completed"
          : status;
      };
      const publishChildRoot = Effect.fnUntraced(function* (
        context: ChildContext,
        status: OrchestrationV2TurnItemStatus,
        time: DateTime.Utc,
      ) {
        context.status = status;
        yield* emit({
          type: "node.updated",
          driver: MUSE_PROVIDER,
          node: {
            id: context.rootNodeId,
            threadId: context.childThreadId,
            runId: null,
            parentNodeId: null,
            rootNodeId: context.rootNodeId,
            kind: "root_turn",
            status,
            countsForRun: false,
            providerThreadId: null,
            providerTurnId: null,
            nativeItemRef: nativeRef(context.childSessionId),
            runtimeRequestId: null,
            checkpointScopeId: null,
            startedAt: context.appThread.createdAt,
            completedAt: status === "running" || status === "pending" ? null : time,
          },
        });
      });
      const publishChildMessage = Effect.fnUntraced(function* (
        context: ChildContext,
        role: "user" | "assistant",
        text: string,
        suffix: "prompt" | "result",
        time: DateTime.Utc,
      ) {
        const identity = childItemIdentity(context, suffix);
        const artifacts = makeSubagentConversationArtifacts({
          messageId: idAllocator.derive.messageFromProviderItem({
            driver: MUSE_PROVIDER,
            nativeItemId: identity,
          }),
          ...(role === "user" ? { senderThreadId: context.parentThreadId } : {}),
          turnItemId: idAllocator.derive.turnItemFromProviderItem({
            driver: MUSE_PROVIDER,
            nativeItemId: identity,
          }),
          threadId: context.childThreadId,
          rootNodeId: context.rootNodeId,
          providerThreadId: null,
          providerTurnId: null,
          nativeItemRef: nativeRef(context.childSessionId),
          role,
          text,
          ordinal: suffix === "prompt" ? 1 : 2,
          now: time,
        });
        yield* emit({ type: "message.updated", driver: MUSE_PROVIDER, message: artifacts.message });
        yield* emit({
          type: "turn_item.updated",
          driver: MUSE_PROVIDER,
          turnItem: artifacts.turnItem,
        });
      });
      const ensureChildContext = Effect.fnUntraced(function* (
        turn: ActiveTurn,
        item: MuseItem,
        parentNodeId: NodeId,
        title: string,
        prompt: string,
        status: OrchestrationV2TurnItemStatus,
        time: DateTime.Utc,
      ) {
        const existing = childrenByItemId.get(item.itemId);
        const childSessionId = item.childSessionId;
        if (existing || !childSessionId) return existing;
        const childThreadId = idAllocator.derive.threadFromProviderThread({
          driver: MUSE_PROVIDER,
          providerInstanceId: options.instanceId,
          nativeThreadId: childSessionId,
        });
        const appThread = makeSubagentChildThread({
          parentThread: turn.input.appThread,
          childThreadId,
          parentNodeId,
          activeProviderThreadId: null,
          providerInstanceId: options.instanceId,
          modelSelection: turn.input.modelSelection,
          title,
          now: time,
          createdBy: "agent",
          creationSource: "provider",
        });
        const context: ChildContext = {
          childSessionId,
          childThreadId,
          appThread,
          rootNodeId: idAllocator.derive.nodeFromProviderItem({
            driver: MUSE_PROVIDER,
            nativeItemId: `${options.instanceId}:child:${childSessionId}:thread-root`,
          }),
          parentThreadId: turn.input.threadId,
          status,
        };
        childrenByItemId.set(item.itemId, context);
        yield* emit({ type: "app_thread.created", driver: MUSE_PROVIDER, appThread });
        yield* publishChildRoot(context, status, time);
        if (prompt) yield* publishChildMessage(context, "user", prompt, "prompt", time);
        return context;
      });
      const publishNativeSubagent = Effect.fnUntraced(function* (
        turn: ActiveTurn,
        item: MuseItem,
        base: ReturnType<typeof baseItem> & {
          readonly status: OrchestrationV2TurnItemStatus;
          readonly completedAt: DateTime.Utc | null;
          readonly title: string | null;
        },
        status: OrchestrationV2TurnItemStatus,
        time: DateTime.Utc,
      ) {
        const prompt = item.objective ?? item.fallbackText ?? "";
        const settled = status !== "running" && status !== "pending";
        const endKey = `subagent:${item.itemId}`;
        if (settled && !agentEndedAt.has(endKey)) agentEndedAt.set(endKey, time);
        if (!settled) agentEndedAt.delete(endKey);
        const completedAt = settled ? (agentEndedAt.get(endKey) ?? time) : null;
        if (!agentTitles.has(endKey))
          agentTitles.set(
            endKey,
            subagentThreadTitle({
              parentTitle: turn.input.appThread.title,
              prompt,
              title: item.role ?? null,
              ordinal: childrenByItemId.size + 1,
            }),
          );
        const title = agentTitles.get(endKey)!;
        const context = yield* ensureChildContext(
          turn,
          item,
          base.nodeId,
          title,
          prompt,
          status,
          time,
        );
        const resultText =
          item.result?.text ??
          item.result?.summary ??
          (status === "failed" ? item.failureReason : undefined);
        const result = resultText ?? null;
        const nativeTaskRef = nativeRef(backgroundTaskId(item));
        const subagent: OrchestrationV2Subagent = {
          id: base.nodeId,
          threadId: base.threadId,
          runId: base.runId,
          parentNodeId: turn.input.rootNodeId,
          origin: "provider_native",
          createdBy: "agent",
          driver: MUSE_PROVIDER,
          providerInstanceId: options.instanceId,
          providerThreadId: base.providerThreadId,
          childThreadId: context?.childThreadId ?? null,
          nativeTaskRef,
          prompt,
          title,
          model: null,
          status,
          result,
          startedAt: base.startedAt,
          completedAt,
          updatedAt: time,
        };
        yield* emit({ type: "subagent.updated", driver: MUSE_PROVIDER, subagent });
        yield* emit({
          type: "node.updated",
          driver: MUSE_PROVIDER,
          node: {
            id: base.nodeId,
            threadId: base.threadId,
            runId: base.runId,
            parentNodeId: turn.input.rootNodeId,
            rootNodeId: turn.input.rootNodeId,
            kind: "subagent",
            status,
            countsForRun: false,
            providerThreadId: base.providerThreadId,
            providerTurnId: base.providerTurnId,
            nativeItemRef: nativeTaskRef,
            runtimeRequestId: null,
            checkpointScopeId: null,
            startedAt: base.startedAt,
            completedAt,
          },
        });
        yield* emit({
          type: "turn_item.updated",
          driver: MUSE_PROVIDER,
          turnItem: {
            ...base,
            nativeItemRef: nativeTaskRef,
            type: "subagent",
            status,
            title,
            completedAt,
            subagentId: subagent.id,
            origin: "provider_native",
            driver: MUSE_PROVIDER,
            providerInstanceId: options.instanceId,
            childThreadId: subagent.childThreadId,
            prompt,
            result,
          },
        });
        if (context) {
          if (context.status !== status) yield* publishChildRoot(context, status, time);
          if (settled && result?.trim() && context.result !== result) {
            context.result = result;
            yield* publishChildMessage(context, "assistant", result, "result", time);
          }
        }
      });
      const syncBackground = Effect.fnUntraced(function* () {
        yield* updateThread({
          pendingBackgroundTasks: [...observedChildren].flatMap(([itemId, owner]) => {
            const item = owner.items.get(itemId);
            const description = item?.objective ?? item?.entryId ?? item?.fallbackText;
            return [
              {
                taskId: item ? backgroundTaskId(item) : itemId,
                kind:
                  item?.kind === "subagent" ? ("subagent" as const) : ("background_task" as const),
                ...(description ? { description } : {}),
              },
            ];
          }),
        });
      });
      const publishItem = Effect.fnUntraced(function* (
        turn: ActiveTurn,
        item: MuseItem,
        terminal?: OrchestrationV2TurnItem["status"],
      ) {
        // Muse's skill-reminder child runs on every model step; it is housekeeping, not work.
        if (item.kind === "userMessage" || item.kind === "reminderChild") return;
        if (
          item.kind === "toolCall" &&
          item.tool &&
          TOOLS_WITH_NATIVE_ROWS.has(item.tool) &&
          item.status !== "failed"
        )
          return;
        const time = yield* DateTime.now;
        const status = terminal ?? itemStatus(item);
        if (item.kind === "subagent" || item.kind === "workflow") {
          const wasRunning = observedChildren.has(item.itemId);
          if (status === "running") observedChildren.set(item.itemId, turn);
          else if (observedChildren.delete(item.itemId) && active !== turn)
            finishedBackground.push({
              kind: item.kind === "subagent" ? "subagent" : "background_task",
              label: item.objective ?? item.entryId ?? item.fallbackText,
              outcome:
                status === "completed"
                  ? "completed"
                  : status === "cancelled"
                    ? "cancelled"
                    : "failed",
            });
          const running = observedChildren.has(item.itemId);
          // Muse reveals a subagent's ids over several revisions, so a running child is
          // relisted whenever the id its turn item carries moves.
          const listed = thread?.pendingBackgroundTasks?.some(
            (task) => task.taskId === backgroundTaskId(item),
          );
          if (wasRunning !== running || (running && !listed)) yield* syncBackground();
        }
        const streaming = status === "running";
        const base = {
          ...baseItem(turn, item.itemId, time),
          status,
          completedAt: streaming ? null : time,
          title: item.tool ?? null,
        };
        if (item.kind === "subagent") {
          yield* publishNativeSubagent(turn, item, base, status, time);
          return;
        }
        const text = item.text ?? item.summary?.join("\n") ?? item.fallbackText ?? "";
        let turnItem: OrchestrationV2TurnItem;
        if (item.kind === "agentMessage") {
          const messageId = idAllocator.derive.messageFromProviderItem({
            driver: MUSE_PROVIDER,
            nativeItemId: itemIdentity(turn, item.itemId),
          });
          const message: OrchestrationV2ConversationMessage = {
            id: messageId,
            threadId: turn.input.threadId,
            runId: turn.input.runId,
            nodeId: base.nodeId,
            role: "assistant",
            text,
            attachments: [],
            streaming,
            createdBy: "agent",
            creationSource: "provider",
            createdAt: base.startedAt,
            updatedAt: time,
          };
          yield* emit({ type: "message.updated", driver: MUSE_PROVIDER, message });
          turnItem = { ...base, type: "assistant_message", messageId, text, streaming };
        } else if (item.kind === "reasoning") {
          turnItem = { ...base, type: "reasoning", text, streaming };
        } else if (item.kind === "compaction") {
          turnItem = {
            ...base,
            type: "compaction",
            driver: MUSE_PROVIDER,
            summary: text || item.reason,
          };
        } else {
          turnItem = { ...base, ...museToolPresentation(item, status) };
        }
        yield* emit({
          type: "node.updated",
          driver: MUSE_PROVIDER,
          node: {
            id: base.nodeId,
            threadId: base.threadId,
            runId: base.runId,
            parentNodeId: turn.input.rootNodeId,
            rootNodeId: turn.input.rootNodeId,
            kind:
              item.kind === "agentMessage"
                ? "assistant_message"
                : item.kind === "reasoning"
                  ? "reasoning"
                  : "tool_call",
            status,
            countsForRun: false,
            providerThreadId: base.providerThreadId,
            providerTurnId: base.providerTurnId,
            nativeItemRef: base.nativeItemRef,
            runtimeRequestId: null,
            checkpointScopeId: null,
            startedAt: base.startedAt,
            completedAt: base.completedAt,
          },
        });
        yield* emit({ type: "turn_item.updated", driver: MUSE_PROVIDER, turnItem });
        if (item.kind === "workflow") yield* publishWorkflowAgents(turn, item, base, status);
      });
      const publishWorkflowAgents = Effect.fnUntraced(function* (
        turn: ActiveTurn,
        item: MuseItem,
        workflow: { readonly id: OrchestrationV2TurnItem["id"]; readonly nodeId: NodeId },
        workflowStatus: OrchestrationV2TurnItemStatus,
      ) {
        const latest = new Map((item.children ?? []).map((child) => [child.childId, child]));
        for (const [index, child] of [...latest.values()].entries()) {
          const time = yield* DateTime.now;
          const base = baseItem(turn, `${item.itemId}:agent:${child.childId}`, time);
          // Muse marks a failed attempt with `failureKind`, even when its terminal is `completed`.
          const status: OrchestrationV2TurnItemStatus =
            child.terminal === "completed" && child.failureKind === undefined
              ? "completed"
              : child.terminal === "cancelled"
                ? "cancelled"
                : child.terminal !== undefined
                  ? "failed"
                  : workflowStatus !== "running"
                    ? workflowStatus
                    : child.status === "scheduled"
                      ? "pending"
                      : "running";
          const settled = status !== "running" && status !== "pending";
          // Children are re-sent on every workflow change; keep each one's first end time.
          const endKey = `${item.itemId}:${child.childId}:${child.attempt}`;
          if (settled && !agentEndedAt.has(endKey)) agentEndedAt.set(endKey, time);
          // Later revisions drop the label; keep the last one seen.
          if (child.label?.trim()) agentTitles.set(endKey, child.label.trim());
          const title = agentTitles.get(endKey) || `Agent ${index + 1}`;
          const result = child.failureReason ?? child.failureKind ?? null;
          const subagent: OrchestrationV2Subagent = {
            id: base.nodeId,
            threadId: base.threadId,
            runId: base.runId,
            parentNodeId: workflow.nodeId,
            origin: "provider_native",
            createdBy: "agent",
            driver: MUSE_PROVIDER,
            providerInstanceId: options.instanceId,
            providerThreadId: base.providerThreadId,
            childThreadId: null,
            nativeTaskRef: nativeRef(child.childId),
            prompt: title,
            title,
            model: null,
            status,
            result,
            startedAt: base.startedAt,
            completedAt: settled ? (agentEndedAt.get(endKey) ?? time) : null,
            updatedAt: time,
          };
          yield* emit({ type: "subagent.updated", driver: MUSE_PROVIDER, subagent });
          yield* emit({
            type: "node.updated",
            driver: MUSE_PROVIDER,
            node: {
              id: base.nodeId,
              threadId: base.threadId,
              runId: base.runId,
              parentNodeId: workflow.nodeId,
              rootNodeId: turn.input.rootNodeId,
              kind: "subagent",
              status,
              countsForRun: false,
              providerThreadId: base.providerThreadId,
              providerTurnId: base.providerTurnId,
              nativeItemRef: subagent.nativeTaskRef,
              runtimeRequestId: null,
              checkpointScopeId: null,
              startedAt: base.startedAt,
              completedAt: subagent.completedAt,
            },
          });
          yield* emit({
            type: "turn_item.updated",
            driver: MUSE_PROVIDER,
            turnItem: {
              ...base,
              nativeItemRef: subagent.nativeTaskRef,
              parentItemId: workflow.id,
              type: "subagent",
              status,
              title,
              completedAt: subagent.completedAt,
              subagentId: subagent.id,
              origin: "provider_native",
              driver: MUSE_PROVIDER,
              providerInstanceId: options.instanceId,
              childThreadId: null,
              prompt: title,
              result,
            },
          });
        }
      });
      const settleObservedChildren = Effect.fnUntraced(function* (
        status: "failed" | "cancelled" | "interrupted",
      ) {
        for (const [itemId, owner] of observedChildren) {
          const item = owner.items.get(itemId);
          if (item) yield* publishItem(owner, item, status);
        }
        observedChildren.clear();
        if (thread?.pendingBackgroundTasks?.length) yield* syncBackground();
        for (const entry of pending.values()) yield* resolvePending(entry, "cancelled");
      });
      const resolvePending = Effect.fnUntraced(function* (
        entry: PendingRequest,
        status: "resolved" | "cancelled",
      ) {
        const time = yield* DateTime.now;
        entry.request = {
          ...entry.request,
          ...(status === "resolved" ? entry.response : undefined),
          status,
          resolvedAt: time,
          responseCapability: { type: "not_resumable", reason: "This Muse request has ended." },
        };
        entry.node = {
          ...entry.node,
          status: status === "resolved" ? "completed" : "cancelled",
          completedAt: time,
        };
        entry.item = {
          ...entry.item,
          status: status === "resolved" ? "completed" : "cancelled",
          completedAt: time,
          updatedAt: time,
        };
        pending.delete(entry.request.id);
        yield* emit({
          type: "runtime_request.updated",
          driver: MUSE_PROVIDER,
          threadId: input.threadId,
          runtimeRequest: entry.request,
        });
        yield* emit({ type: "node.updated", driver: MUSE_PROVIDER, node: entry.node });
        yield* emit({ type: "turn_item.updated", driver: MUSE_PROVIDER, turnItem: entry.item });
      });
      const finish = Effect.fnUntraced(function* (
        turn: ActiveTurn,
        status: "completed" | "cancelled" | "interrupted" | "failed",
        detail?: string,
        disposition: "reusable" | "broken" = "reusable",
        quota?: { readonly resetsAtMs: number },
      ) {
        if (active !== turn || seenTerminals.has(turn.nativeId)) return;
        seenTerminals.add(turn.nativeId);
        const completedAt = yield* DateTime.now;
        for (const item of turn.items.values()) {
          if (
            (item.kind === "subagent" || item.kind === "workflow") &&
            item.status === "inProgress" &&
            status === "completed" &&
            disposition === "reusable"
          )
            continue;
          if (turn.dirty.has(item.itemId) || item.status === "inProgress")
            yield* publishItem(turn, item, item.status === "inProgress" ? status : undefined);
        }
        turn.dirty.clear();
        for (const entry of pending.values())
          if (entry.request.providerTurnId !== null) yield* resolvePending(entry, "cancelled");
        turn.providerTurn = { ...turn.providerTurn, status, completedAt };
        lastProviderTurn = turn.providerTurn;
        yield* emit({
          type: "provider_turn.updated",
          driver: MUSE_PROVIDER,
          threadId: turn.input.threadId,
          providerTurn: turn.providerTurn,
        });
        yield* updateThread({
          status: disposition === "broken" ? "error" : "idle",
          ...(!turn.compact && status === "completed"
            ? { nativeConversationHeadRef: nativeRef(turn.nativeId) }
            : {}),
        });
        yield* updateSession(disposition === "broken" ? "error" : "ready", detail ?? null);
        active = undefined;
        if (status === "failed") {
          const usageLimited =
            disposition === "reusable" && (quota !== undefined || isMuseUsageLimitFailure(detail));
          const failure = makeProviderFailure({
            class:
              disposition === "broken"
                ? "transport_error"
                : usageLimited
                  ? "usage_limit"
                  : "provider_error",
            message: detail ?? "Muse turn failed.",
            ...(usageLimited
              ? {
                  resetAt: museUsageLimitResetAt(
                    latestSubscriptionUsage,
                    DateTime.toEpochMillis(completedAt),
                    { quota, message: detail },
                  ),
                }
              : {}),
          });
          const base = baseItem(turn, `failure:${turn.nativeId}`, completedAt);
          yield* emit({
            type: "turn_item.updated",
            driver: MUSE_PROVIDER,
            turnItem: {
              ...base,
              type: "error",
              status: "failed",
              title: usageLimited ? "Usage limit reached" : null,
              completedAt,
              failure,
            },
          });
          yield* emit({
            type: "turn.terminal",
            driver: MUSE_PROVIDER,
            providerThreadId: turn.providerTurn.providerThreadId,
            providerTurnId: turn.providerTurn.id,
            runOrdinal: turn.input.runOrdinal,
            status,
            failure,
            failureItemOrdinal: base.ordinal,
            threadDisposition: disposition,
          });
        } else {
          yield* emit({
            type: "turn.terminal",
            driver: MUSE_PROVIDER,
            providerThreadId: turn.providerTurn.providerThreadId,
            providerTurnId: turn.providerTurn.id,
            runOrdinal: turn.input.runOrdinal,
            status,
            failure: null,
            threadDisposition: disposition,
          });
        }
        yield* Deferred.succeed(turn.done, undefined);
      });
      const failHost = Effect.fnUntraced(function* (cause: unknown) {
        if (closed || broken) return;
        hostEpoch++;
        // Registration can replace the host while failure events are consumed.
        const failed = host;
        const turn = active;
        broken = true;
        relaunchable = !turn;
        wake = undefined;
        const rootCause = Cause.isCause(cause) ? Cause.squash(cause) : cause;
        const failure = isOpenSessionError(rootCause) ? rootCause.cause : rootCause;
        const detail = isProtocolError(failure)
          ? failure.detail
          : failure instanceof Error
            ? failure.message
            : "Muse transport failed.";
        if (turn) yield* finish(turn, "failed", detail, "broken");
        else {
          yield* updateThread({ status: "error" });
          yield* updateSession("error", detail);
        }
        yield* settleObservedChildren("failed");
        if (turn) yield* Queue.fail(events, protocolError(detail, cause));
        yield* Effect.tryPromise({
          try: () => failed.close(),
          catch: (cause) => new MuseSdkError({ operation: "close", cause }),
        }).pipe(Effect.ignore, Effect.forkIn(scope));
      });
      const owns = (turn: ActiveTurn, turnId: string) =>
        turnId === turn.nativeId || turn.joined.has(turnId);
      const decideApproval = Effect.fnUntraced(function* (
        entry: PendingRequest,
        decision: ProviderApprovalDecision | undefined,
      ) {
        if (entry.native.type !== "approval") return;
        const approval = entry.native.value;
        const choice = decision && museApprovalChoices(approval).get(decision);
        if (!choice) return yield* protocolError("Muse did not offer this approval decision");
        // Recorded first: Muse can settle the approval before it acknowledges the command.
        entry.response = { decision };
        yield* request("approval/decide", {
          approvalId: approval.approvalId,
          requirementId: approval.currentRequirementId,
          choiceId: choice.choiceId,
        }).pipe(Effect.tapError(() => Effect.sync(() => delete entry.response)));
      });
      const showRequest = Effect.fnUntraced(function* (entry: PendingRequest) {
        entry.shown = true;
        yield* emit({
          type: "runtime_request.updated",
          driver: MUSE_PROVIDER,
          threadId: entry.node.threadId,
          runtimeRequest: entry.request,
        });
        yield* emit({ type: "node.updated", driver: MUSE_PROVIDER, node: entry.node });
        yield* emit({ type: "turn_item.updated", driver: MUSE_PROVIDER, turnItem: entry.item });
        yield* updateSession("waiting");
      });
      /**
       * A workflow child's approval is runless: the turn that started the workflow
       * may end long before the child asks, and T3 keeps a runless request on the
       * thread until Muse settles it.
       */
      const publishRequest = Effect.fnUntraced(function* (native: PendingRequest["native"]) {
        const child = native.type === "approval" && native.value.subagentOrigin !== undefined;
        const turn = child ? undefined : active;
        if (
          !thread ||
          (!child && !turn) ||
          native.value.sessionId !== nativeSessionId ||
          (turn && native.value.turnId && !owns(turn, native.value.turnId))
        )
          return;
        const nativeId =
          native.type === "approval" ? native.value.approvalId : native.value.userInputId;
        if (turn?.settledRequests.has(`${native.type}:${nativeId}`)) return;
        const previous = [...pending.values()].find(
          (entry) =>
            entry.native.type === native.type &&
            entry.request.nativeRequestRef?.nativeId === nativeId,
        );
        const providerTurnId = turn?.providerTurn.id ?? null;
        const threadId = turn?.input.threadId ?? thread.appThreadId ?? input.threadId;
        const requestId =
          previous?.request.id ??
          (yield* idAllocator.allocate
            .runtimeRequest({
              driver: MUSE_PROVIDER,
              ...(providerTurnId ? { providerTurnId } : {}),
              nativeRequestId: nativeId,
            })
            .pipe(
              Effect.mapError((cause) => protocolError("Cannot allocate Muse request", cause)),
            ));
        const time = yield* DateTime.now;
        const nodeId = idAllocator.derive.approvalNode({ requestId });
        const subject = native.type === "approval" ? native.value.subject : undefined;
        const kind = !subject
          ? "user_input"
          : subject.kind === "shell"
            ? "command"
            : subject.kind !== "fileAccess"
              ? "permission"
              : subject.access === "read"
                ? "file-read"
                : "file-change";
        const runtimeRequest: OrchestrationV2RuntimeRequest = {
          id: requestId,
          nodeId,
          providerTurnId,
          nativeRequestRef: nativeRef(nativeId),
          kind,
          status: "pending",
          responseCapability: { type: "live", providerSessionId: input.providerSessionId },
          createdAt: previous?.request.createdAt ?? time,
          resolvedAt: null,
        };
        const node: OrchestrationV2ExecutionNode = {
          id: nodeId,
          threadId,
          runId: turn?.input.runId ?? null,
          parentNodeId: turn?.input.rootNodeId ?? null,
          rootNodeId: turn?.input.rootNodeId ?? nodeId,
          kind: native.type === "approval" ? "approval_request" : "user_input_request",
          status: "waiting",
          countsForRun: false,
          providerThreadId: thread.id,
          providerTurnId,
          nativeItemRef: nativeRef(nativeId),
          runtimeRequestId: requestId,
          checkpointScopeId: null,
          startedAt: runtimeRequest.createdAt,
          completedAt: null,
        };
        const latestTurn = active?.providerTurn ?? lastProviderTurn;
        const base = {
          ...(turn
            ? baseItem(turn, `request:${nativeId}`, time)
            : {
                threadId,
                runId: null,
                providerThreadId: thread.id,
                providerTurnId: null,
                nativeItemRef: nativeRef(nativeId),
                parentItemId: null,
                ordinal: previous?.item.ordinal ?? ((latestTurn?.ordinal ?? 0) + 1) * 100,
                startedAt: runtimeRequest.createdAt,
                updatedAt: time,
              }),
          id: idAllocator.derive.approvalTurnItem({ requestId }),
          nodeId,
          status: "waiting" as const,
          title: null,
          completedAt: null,
        };
        const item: OrchestrationV2TurnItem =
          native.type === "approval"
            ? {
                ...base,
                type: "approval_request",
                requestId,
                requestKind: kind === "user_input" ? "command" : kind,
                prompt:
                  native.value.subject.command ??
                  native.value.subject.path ??
                  native.value.subject.host ??
                  native.value.subject.target ??
                  native.value.toolName ??
                  "Muse requests permission",
                options: museApprovalOptions(native.value),
              }
            : {
                ...base,
                type: "user_input_request",
                requestId,
                questions: native.value.questions.map((question) => ({
                  id: question.id,
                  header: question.header || "Question",
                  question: question.question,
                  options: question.options.map((option) => ({
                    label: option.label,
                    description: option.description || option.label,
                  })),
                  multiSelect: question.selection.mode === "multiple",
                  allowCustomAnswer: true,
                  required: true,
                })),
              };
        // Muse does not propagate allowAll to workflow children; T3 answers for them.
        const autoApprove = child && input.runtimePolicy.runtimeMode === "full-access";
        const entry: PendingRequest = {
          native,
          request: runtimeRequest,
          node,
          item,
          shown: !autoApprove || previous?.shown === true,
        };
        pending.set(requestId, entry);
        if (entry.shown) yield* showRequest(entry);
        if (autoApprove)
          yield* decideApproval(entry, "accept").pipe(
            Effect.catch(() =>
              Effect.gen(function* () {
                // Native updates may settle or replace this entry while the RPC is in flight.
                if (!closed && !broken && pending.get(requestId) === entry)
                  yield* showRequest(entry);
              }).pipe(eventPermit.withPermits(1)),
            ),
            Effect.forkIn(scope),
          );
      });
      const handleRequestEvent = Effect.fnUntraced(function* (
        method: string,
        params: Record<string, unknown>,
        turn: ActiveTurn | undefined,
      ) {
        switch (method) {
          case "approval/requested":
          case "approval/updated":
            if (
              method === "approval/updated" &&
              ![...pending.values()].some(
                (entry) =>
                  entry.native.type === "approval" &&
                  entry.native.value.approvalId === params.approvalId,
              )
            )
              return;
            return yield* publishRequest({
              type: "approval",
              value: yield* decode(MuseApproval, params),
            });
          case "userInput/requested":
            return yield* publishRequest({
              type: "question",
              value: yield* decode(MuseUserInput, params),
            });
          case "approval/resolved":
          case "userInput/settled": {
            const id = method === "approval/resolved" ? params.approvalId : params.userInputId;
            if (typeof id === "string")
              turn?.settledRequests.add(
                `${method === "approval/resolved" ? "approval" : "question"}:${id}`,
              );
            const entry = [...pending.values()].find(
              (candidate) => candidate.request.nativeRequestRef?.nativeId === id,
            );
            if (entry) {
              const native =
                method === "approval/resolved" && typeof params.decision === "string"
                  ? museApprovalDecision({ decision: params.decision, scope: "once" })
                  : undefined;
              if (!entry.response && native) entry.response = { decision: native };
              yield* resolvePending(entry, "resolved");
            }
            if (![...pending.values()].some((candidate) => candidate.shown))
              yield* updateSession(active ? "running" : "ready");
          }
        }
      });
      const handleNotification = Effect.fnUntraced(function* (method: string, data: unknown) {
        const params = yield* decode(recordSchema, data);
        // usage/changed is account-wide and carries no session ID.
        if (method === "usage/changed") {
          latestSubscriptionUsage = yield* decode(MuseSubscriptionUsage, params);
          return;
        }
        if (params.sessionId !== nativeSessionId) return;
        if (method === "view/gap")
          return yield* protocolError("Muse delivery gap requires session recovery");
        if (method === "session/contextUsage") {
          const usage = yield* decode(MuseContextUsage, params);
          const currentTurn = active?.providerTurn ?? lastProviderTurn;
          const updatedAt = DateTime.formatIso(yield* DateTime.now);
          const tokenUsage = {
            ...currentTurn?.tokenUsage,
            usedTokens: usage.usedTokens,
            maxTokens: usage.windowTokens ?? currentTurn?.tokenUsage?.maxTokens ?? undefined,
            updatedAt,
          };
          yield* updateThread({ contextUsage: tokenUsage });
          if (currentTurn) {
            const updated = { ...currentTurn, tokenUsage };
            if (active) active.providerTurn = updated;
            else lastProviderTurn = updated;
            yield* emit({
              type: "provider_turn.updated",
              driver: MUSE_PROVIDER,
              providerTurn: updated,
            });
          }
          return;
        }
        const itemEvent = ["item/started", "item/updated", "item/completed"].includes(method)
          ? (yield* decode(MuseItemEvent, params)).item
          : undefined;
        if (itemEvent) {
          const owner = observedChildren.get(itemEvent.itemId);
          if (owner && owner !== active && itemEvent.turnId === owner.nativeId) {
            const previous = owner.items.get(itemEvent.itemId);
            if (!previous || itemEvent.revision > previous.revision) {
              owner.items.set(itemEvent.itemId, itemEvent);
              yield* publishItem(owner, itemEvent);
            }
            return;
          }
        }
        // Child approvals use their own run IDs and can outlive turns; bypass turn routing.
        if (params.subagentOrigin !== undefined && method.startsWith("approval/"))
          return yield* handleRequestEvent(method, params, undefined);
        if (
          method === "turn/started" &&
          typeof params.turnId === "string" &&
          params.turnId !== active?.nativeId &&
          params.turnId !== wake?.nativeId
        ) {
          if (active && !active.compact) active.joined.add(params.turnId);
          else if (!active && !wake) {
            const held = { nativeId: params.turnId, events: [] };
            wake = held;
            const notification = backgroundWorkNotification(finishedBackground.splice(0));
            if (thread?.appThreadId && options.continuationRequests)
              yield* options.continuationRequests.offer({
                threadId: thread.appThreadId,
                providerThreadId: thread.id,
                driver: MUSE_PROVIDER,
                detail: null,
                ...(notification ? { notification } : {}),
                dispatchIfCurrent: (dispatch) =>
                  wake === held ? Effect.asSome(dispatch) : Effect.succeedNone,
                clearIfCurrent: () =>
                  Effect.sync(() => {
                    if (wake === held) wake = undefined;
                  }),
              });
          }
        }
        if (wake && active?.nativeId !== wake.nativeId) {
          const turnId = typeof params.turnId === "string" ? params.turnId : itemEvent?.turnId;
          if (turnId === wake.nativeId) {
            wake.events.push([method, data]);
            return;
          }
        }
        const turn = active;
        if (!turn) return;
        if (typeof params.turnId === "string" && !owns(turn, params.turnId) && !turn.compact)
          return;
        switch (method) {
          case "item/started":
          case "item/updated":
          case "item/completed": {
            const item = itemEvent!;
            if (
              item.turnId &&
              !owns(turn, item.turnId) &&
              !(turn.compact && item.kind === "compaction")
            )
              return;
            const previous = turn.items.get(item.itemId);
            if (previous && previous.revision >= item.revision) return;
            turn.items.set(item.itemId, item);
            turn.dirty.delete(item.itemId);
            yield* publishItem(turn, item);
            if (turn.compact && item.kind === "compaction" && item.status !== "inProgress") {
              yield* finish(
                turn,
                item.status === "completed" && (!item.outcome || item.outcome === "compacted")
                  ? "completed"
                  : item.status === "cancelled"
                    ? "cancelled"
                    : "failed",
                item.failureReason ?? item.reason,
              );
            }
            break;
          }
          case "item/delta": {
            const delta = yield* decode(MuseDelta, params);
            const previous = turn.items.get(delta.itemId);
            if (!previous || previous.status !== "inProgress") return;
            const field = delta.field ?? "text";
            let item = previous;
            if (field === "text") item = { ...previous, text: (previous.text ?? "") + delta.delta };
            else if (field === "output" || field === "visibleOutput")
              item = { ...previous, visibleOutput: (previous.visibleOutput ?? "") + delta.delta };
            else if (field.startsWith("summary.")) {
              const index = Number(field.slice(8));
              if (Number.isSafeInteger(index) && index >= 0 && index < 100) {
                const summary = [...(previous.summary ?? [])];
                summary[index] = (summary[index] ?? "") + delta.delta;
                item = { ...previous, summary };
              }
            }
            if (item === previous) return;
            turn.items.set(item.itemId, item);
            turn.dirty.add(item.itemId);
            if (!turn.flushScheduled) {
              turn.flushScheduled = true;
              yield* Effect.sleep(50).pipe(
                Effect.andThen(Queue.offer(inbox, { type: "flush", turn })),
                Effect.forkIn(scope),
              );
            }
            break;
          }
          case "turn/completed": {
            if (turn.compact) return;
            const result = yield* decode(MuseTurnCompleted, params);
            // A joined Muse turn ending does not end this run; its own turn does.
            if (result.turnId !== turn.nativeId) break;
            if (result.usage) {
              const usage = result.usage;
              turn.providerTurn = {
                ...turn.providerTurn,
                turnTokenUsage: {
                  usageScope: "main_agent",
                  usageStatus: "complete",
                  hasSubagents: [...turn.items.values()].some((item) => item.kind === "subagent"),
                  inputTokens: turn.providerTurn.turnTokenUsage?.inputTokens ?? usage.inputTokens,
                  outputTokens: usage.outputTokens,
                  cachedInputTokens: usage.cacheReadTokens ?? usage.cachedTokens,
                  reasoningTokens: usage.reasoningTokens,
                  ...(usage.cacheWriteTokens === undefined
                    ? {}
                    : { cacheCreationTokens: usage.cacheWriteTokens }),
                },
              };
            }
            const status =
              result.terminal === "completed"
                ? "completed"
                : result.terminal === "cancelled"
                  ? turn.interruptRequested
                    ? "interrupted"
                    : "cancelled"
                  : "failed";
            yield* finish(
              turn,
              status,
              result.error?.message ?? result.reason,
              "reusable",
              result.error?.quota,
            );
            break;
          }
          case "approval/requested":
          case "approval/updated":
          case "approval/resolved":
          case "userInput/requested":
          case "userInput/settled":
            yield* handleRequestEvent(method, params, turn);
            break;
          case "session/tokenUsage": {
            const usage = yield* decode(MuseTokenUsageEvent, params);
            const previous = turn.providerTurn.turnTokenUsage;
            const contextUsage = thread?.contextUsage;
            turn.providerTurn = {
              ...turn.providerTurn,
              ...(contextUsage
                ? {
                    tokenUsage: {
                      ...turn.providerTurn.tokenUsage,
                      usedTokens: contextUsage.usedTokens,
                      inputTokens: usage.usage.inputTokens,
                      outputTokens: usage.usage.outputTokens,
                      cachedInputTokens: usage.usage.cacheReadTokens ?? usage.usage.cachedTokens,
                      reasoningOutputTokens: usage.usage.reasoningTokens,
                      updatedAt: DateTime.formatIso(yield* DateTime.now),
                    },
                  }
                : {}),
              turnTokenUsage: {
                usageScope: "main_agent",
                usageStatus: "partial",
                hasSubagents: [...turn.items.values()].some((item) => item.kind === "subagent"),
                inputTokens: (previous?.inputTokens ?? 0) + usage.promptTokens,
                outputTokens: (previous?.outputTokens ?? 0) + usage.usage.outputTokens,
                cachedInputTokens:
                  (previous?.cachedInputTokens ?? 0) +
                  (usage.usage.cacheReadTokens ?? usage.usage.cachedTokens),
                ...(usage.usage.cacheWriteTokens === undefined &&
                previous?.cacheCreationTokens === undefined
                  ? {}
                  : {
                      cacheCreationTokens:
                        (previous?.cacheCreationTokens ?? 0) + (usage.usage.cacheWriteTokens ?? 0),
                    }),
                reasoningTokens: (previous?.reasoningTokens ?? 0) + usage.usage.reasoningTokens,
              },
            };
            yield* emit({
              type: "provider_turn.updated",
              driver: MUSE_PROVIDER,
              providerTurn: turn.providerTurn,
            });
            break;
          }
          case "session/todoListChanged": {
            const todo = yield* decode(MuseTodoList, params);
            const steps: ReadonlyArray<OrchestrationV2PlanStep> = todo.items
              .filter((item) => item.text.trim() && item.status !== "cancelled")
              .map((item, index) => ({
                id: `${turn.nativeId}:todo:${index}`,
                text: item.text.trim(),
                status:
                  item.status === "completed"
                    ? "completed"
                    : item.status === "inProgress"
                      ? "running"
                      : "pending",
              }));
            const time = yield* DateTime.now;
            const base = baseItem(turn, "todo", time);
            const planId =
              turn.todoPlanId ??
              (yield* idAllocator.allocate
                .plan({
                  threadId: turn.input.threadId,
                  runId: turn.input.runId,
                  driver: MUSE_PROVIDER,
                })
                .pipe(
                  Effect.mapError((cause) =>
                    protocolError("Cannot allocate Muse todo list", cause),
                  ),
                ));
            turn.todoPlanId = planId;
            yield* emit({
              type: "plan.updated",
              driver: MUSE_PROVIDER,
              plan: {
                id: planId,
                threadId: turn.input.threadId,
                runId: turn.input.runId,
                nodeId: base.nodeId,
                kind: "todo_list",
                status: steps.every((step) => step.status === "completed") ? "completed" : "active",
                steps,
              },
            });
            yield* emit({
              type: "node.updated",
              driver: MUSE_PROVIDER,
              node: {
                id: base.nodeId,
                threadId: base.threadId,
                runId: base.runId,
                parentNodeId: turn.input.rootNodeId,
                rootNodeId: turn.input.rootNodeId,
                kind: "todo_list",
                status: "completed",
                countsForRun: false,
                providerThreadId: base.providerThreadId,
                providerTurnId: base.providerTurnId,
                nativeItemRef: null,
                runtimeRequestId: null,
                checkpointScopeId: null,
                startedAt: base.startedAt,
                completedAt: time,
              },
            });
            yield* emit({
              type: "turn_item.updated",
              driver: MUSE_PROVIDER,
              turnItem: {
                ...base,
                nativeItemRef: null,
                type: "todo_list",
                status: "completed",
                title: null,
                completedAt: time,
                planId,
                steps,
              },
            });
            break;
          }
          case "turn/retryScheduled": {
            const retry = yield* decode(MuseTurnRetryScheduled, params);
            const time = yield* DateTime.now;
            yield* emit({
              type: "turn_item.updated",
              driver: MUSE_PROVIDER,
              turnItem: {
                ...baseItem(turn, `retry:${retry.nextAttempt}`, time),
                type: "system_notice",
                status: "completed",