@devries-cameron20 / t3code Mirror · read-only / commits / 59a383e1ea
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 25, 07:30 UTC

Add Effect.fn refactor checklist (#1476)

Julius Marminge committed Mar 27, 2026 at 17:35 UTC 59a383e1ea4914ea12d3551dce2f715b59218618
2 files changed +2165 -2041
apps/server/src/provider/Layers/ClaudeAdapter.ts
+1982 -2041
@@ -552,69 +552,67 @@ function buildClaudeImageContentBlock(input: {
552 };
553 }
554
555 -function buildUserMessageEffect(
555 +const buildUserMessageEffect = Effect.fn("buildUserMessageEffect")(function* (
556 input: ProviderSendTurnInput,
557 dependencies: {
558 readonly fileSystem: FileSystem.FileSystem;
559 readonly attachmentsDir: string;
560 },
561 -): Effect.Effect<SDKUserMessage, ProviderAdapterRequestError> {
562 - return Effect.gen(function* () {
563 - const text = buildPromptText(input);
564 - const sdkContent: Array<Record<string, unknown>> = [];
561 +) {
562 + const text = buildPromptText(input);
563 + const sdkContent: Array<Record<string, unknown>> = [];
564
566 - if (text.length > 0) {
567 - sdkContent.push({ type: "text", text });
568 - }
565 + if (text.length > 0) {
566 + sdkContent.push({ type: "text", text });
567 + }
568
570 - for (const attachment of input.attachments ?? []) {
571 - if (attachment.type !== "image") {
572 - continue;
573 - }
569 + for (const attachment of input.attachments ?? []) {
570 + if (attachment.type !== "image") {
571 + continue;
572 + }
573
575 - if (!SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType)) {
576 - return yield* new ProviderAdapterRequestError({
577 - provider: PROVIDER,
578 - method: "turn/start",
579 - detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`,
580 - });
581 - }
574 + if (!SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType)) {
575 + return yield* new ProviderAdapterRequestError({
576 + provider: PROVIDER,
577 + method: "turn/start",
578 + detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`,
579 + });
580 + }
581
583 - const attachmentPath = resolveAttachmentPath({
584 - attachmentsDir: dependencies.attachmentsDir,
585 - attachment,
582 + const attachmentPath = resolveAttachmentPath({
583 + attachmentsDir: dependencies.attachmentsDir,
584 + attachment,
585 + });
586 + if (!attachmentPath) {
587 + return yield* new ProviderAdapterRequestError({
588 + provider: PROVIDER,
589 + method: "turn/start",
590 + detail: `Invalid attachment id '${attachment.id}'.`,
591 });
587 - if (!attachmentPath) {
588 - return yield* new ProviderAdapterRequestError({
589 - provider: PROVIDER,
590 - method: "turn/start",
591 - detail: `Invalid attachment id '${attachment.id}'.`,
592 - });
593 - }
592 + }
593
595 - const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe(
596 - Effect.mapError(
597 - (cause) =>
598 - new ProviderAdapterRequestError({
599 - provider: PROVIDER,
600 - method: "turn/start",
601 - detail: toMessage(cause, "Failed to read attachment file."),
602 - cause,
603 - }),
604 - ),
605 - );
594 + const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe(
595 + Effect.mapError(
596 + (cause) =>
597 + new ProviderAdapterRequestError({
598 + provider: PROVIDER,
599 + method: "turn/start",
600 + detail: toMessage(cause, "Failed to read attachment file."),
601 + cause,
602 + }),
603 + ),
604 + );
605
607 - sdkContent.push(
608 - buildClaudeImageContentBlock({
609 - mimeType: attachment.mimeType,
610 - bytes,
611 - }),
612 - );
613 - }
606 + sdkContent.push(
607 + buildClaudeImageContentBlock({
608 + mimeType: attachment.mimeType,
609 + bytes,
610 + }),
611 + );
612 + }
613
615 - return buildUserMessage({ sdkContent });
616 - });
617 -}
614 + return buildUserMessage({ sdkContent });
615 +});
616
617 function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStatus {
618 if (result.subtype === "success") {
@@ -911,2198 +909,2141 @@ function sdkNativeItemId(message: SDKMessage): string | undefined {
909 return undefined;
910 }
911
914 -function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
915 - return Effect.gen(function* () {
916 - const fileSystem = yield* FileSystem.FileSystem;
917 - const serverConfig = yield* ServerConfig;
918 - const nativeEventLogger =
919 - options?.nativeEventLogger ??
920 - (options?.nativeEventLogPath !== undefined
921 - ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
922 - stream: "native",
923 - })
924 - : undefined);
925 -
926 - const createQuery =
927 - options?.createQuery ??
928 - ((input: {
929 - readonly prompt: AsyncIterable<SDKUserMessage>;
930 - readonly options: ClaudeQueryOptions;
931 - }) => query({ prompt: input.prompt, options: input.options }) as ClaudeQueryRuntime);
932 -
933 - const sessions = new Map<ThreadId, ClaudeSessionContext>();
934 - const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
935 - const serverSettingsService = yield* ServerSettingsService;
936 -
937 - const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
938 - const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.makeUnsafe(id));
939 - const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
940 -
941 - const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
942 - Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
943 -
944 - const logNativeSdkMessage = (
945 - context: ClaudeSessionContext,
946 - message: SDKMessage,
947 - ): Effect.Effect<void> =>
948 - Effect.gen(function* () {
949 - if (!nativeEventLogger) {
950 - return;
951 - }
912 +const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
913 + options?: ClaudeAdapterLiveOptions,
914 +) {
915 + const fileSystem = yield* FileSystem.FileSystem;
916 + const serverConfig = yield* ServerConfig;
917 + const nativeEventLogger =
918 + options?.nativeEventLogger ??
919 + (options?.nativeEventLogPath !== undefined
920 + ? yield* makeEventNdjsonLogger(options.nativeEventLogPath, {
921 + stream: "native",
922 + })
923 + : undefined);
924 +
925 + const createQuery =
926 + options?.createQuery ??
927 + ((input: {
928 + readonly prompt: AsyncIterable<SDKUserMessage>;
929 + readonly options: ClaudeQueryOptions;
930 + }) => query({ prompt: input.prompt, options: input.options }) as ClaudeQueryRuntime);
931 +
932 + const sessions = new Map<ThreadId, ClaudeSessionContext>();
933 + const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
934 + const serverSettingsService = yield* ServerSettingsService;
935 +
936 + const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
937 + const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.makeUnsafe(id));
938 + const makeEventStamp = () => Effect.all({ eventId: nextEventId, createdAt: nowIso });
939 +
940 + const offerRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
941 + Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid);
942 +
943 + const logNativeSdkMessage = Effect.fn("logNativeSdkMessage")(function* (
944 + context: ClaudeSessionContext,
945 + message: SDKMessage,
946 + ) {
947 + if (!nativeEventLogger) {
948 + return;
949 + }
950
953 - const observedAt = new Date().toISOString();
954 - const itemId = sdkNativeItemId(message);
955 -
956 - yield* nativeEventLogger.write(
957 - {
958 - observedAt,
959 - event: {
960 - id:
961 - "uuid" in message && typeof message.uuid === "string"
962 - ? message.uuid
963 - : crypto.randomUUID(),
964 - kind: "notification",
965 - provider: PROVIDER,
966 - createdAt: observedAt,
967 - method: sdkNativeMethod(message),
968 - ...(typeof message.session_id === "string"
969 - ? { providerThreadId: message.session_id }
970 - : {}),
971 - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
972 - ...(itemId ? { itemId: ProviderItemId.makeUnsafe(itemId) } : {}),
973 - payload: message,
974 - },
975 - },
976 - context.session.threadId,
977 - );
978 - });
951 + const observedAt = new Date().toISOString();
952 + const itemId = sdkNativeItemId(message);
953
980 - const snapshotThread = (
981 - context: ClaudeSessionContext,
982 - ): Effect.Effect<
954 + yield* nativeEventLogger.write(
955 {
984 - threadId: ThreadId;
985 - turns: ReadonlyArray<{
986 - id: TurnId;
987 - items: ReadonlyArray<unknown>;
988 - }>;
956 + observedAt,
957 + event: {
958 + id:
959 + "uuid" in message && typeof message.uuid === "string"
960 + ? message.uuid
961 + : crypto.randomUUID(),
962 + kind: "notification",
963 + provider: PROVIDER,
964 + createdAt: observedAt,
965 + method: sdkNativeMethod(message),
966 + ...(typeof message.session_id === "string"
967 + ? { providerThreadId: message.session_id }
968 + : {}),
969 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
970 + ...(itemId ? { itemId: ProviderItemId.makeUnsafe(itemId) } : {}),
971 + payload: message,
972 + },
973 },
990 - ProviderAdapterValidationError
991 - > =>
992 - Effect.gen(function* () {
993 - const threadId = context.session.threadId;
994 - if (!threadId) {
995 - return yield* new ProviderAdapterValidationError({
996 - provider: PROVIDER,
997 - operation: "readThread",
998 - issue: "Session thread id is not initialized yet.",
999 - });
1000 - }
1001 - return {
1002 - threadId,
1003 - turns: context.turns.map((turn) => ({
1004 - id: turn.id,
1005 - items: [...turn.items],
1006 - })),
1007 - };
974 + context.session.threadId,
975 + );
976 + });
977 +
978 + const snapshotThread = Effect.fn("snapshotThread")(function* (context: ClaudeSessionContext) {
979 + const threadId = context.session.threadId;
980 + if (!threadId) {
981 + return yield* new ProviderAdapterValidationError({
982 + provider: PROVIDER,
983 + operation: "readThread",
984 + issue: "Session thread id is not initialized yet.",
985 });
986 + }
987 + return {
988 + threadId,
989 + turns: context.turns.map((turn) => ({
990 + id: turn.id,
991 + items: [...turn.items],
992 + })),
993 + };
994 + });
995
1010 - const updateResumeCursor = (context: ClaudeSessionContext): Effect.Effect<void> =>
1011 - Effect.gen(function* () {
1012 - const threadId = context.session.threadId;
1013 - if (!threadId) return;
996 + const updateResumeCursor = Effect.fn("updateResumeCursor")(function* (
997 + context: ClaudeSessionContext,
998 + ) {
999 + const threadId = context.session.threadId;
1000 + if (!threadId) return;
1001
1015 - const resumeCursor = {
1016 - threadId,
1017 - ...(context.resumeSessionId ? { resume: context.resumeSessionId } : {}),
1018 - ...(context.lastAssistantUuid ? { resumeSessionAt: context.lastAssistantUuid } : {}),
1019 - turnCount: context.turns.length,
1020 - };
1002 + const resumeCursor = {
1003 + threadId,
1004 + ...(context.resumeSessionId ? { resume: context.resumeSessionId } : {}),
1005 + ...(context.lastAssistantUuid ? { resumeSessionAt: context.lastAssistantUuid } : {}),
1006 + turnCount: context.turns.length,
1007 + };
1008
1022 - context.session = {
1023 - ...context.session,
1024 - resumeCursor,
1025 - updatedAt: yield* nowIso,
1026 - };
1009 + context.session = {
1010 + ...context.session,
1011 + resumeCursor,
1012 + updatedAt: yield* nowIso,
1013 + };
1014 + });
1015 +
1016 + const ensureAssistantTextBlock = Effect.fn("ensureAssistantTextBlock")(function* (
1017 + context: ClaudeSessionContext,
1018 + blockIndex: number,
1019 + options?: {
1020 + readonly fallbackText?: string;
1021 + readonly streamClosed?: boolean;
1022 + },
1023 + ) {
1024 + const turnState = context.turnState;
1025 + if (!turnState) {
1026 + return undefined;
1027 + }
1028 +
1029 + const existing = turnState.assistantTextBlocks.get(blockIndex);
1030 + if (existing && !existing.completionEmitted) {
1031 + if (existing.fallbackText.length === 0 && options?.fallbackText) {
1032 + existing.fallbackText = options.fallbackText;
1033 + }
1034 + if (options?.streamClosed) {
1035 + existing.streamClosed = true;
1036 + }
1037 + return { blockIndex, block: existing };
1038 + }
1039 +
1040 + const block: AssistantTextBlockState = {
1041 + itemId: yield* Random.nextUUIDv4,
1042 + blockIndex,
1043 + emittedTextDelta: false,
1044 + fallbackText: options?.fallbackText ?? "",
1045 + streamClosed: options?.streamClosed ?? false,
1046 + completionEmitted: false,
1047 + };
1048 + turnState.assistantTextBlocks.set(blockIndex, block);
1049 + turnState.assistantTextBlockOrder.push(block);
1050 + return { blockIndex, block };
1051 + });
1052 +
1053 + const createSyntheticAssistantTextBlock = Effect.fn("createSyntheticAssistantTextBlock")(
1054 + function* (context: ClaudeSessionContext, fallbackText: string) {
1055 + const turnState = context.turnState;
1056 + if (!turnState) {
1057 + return undefined;
1058 + }
1059 +
1060 + const blockIndex = turnState.nextSyntheticAssistantBlockIndex;
1061 + turnState.nextSyntheticAssistantBlockIndex -= 1;
1062 + return yield* ensureAssistantTextBlock(context, blockIndex, {
1063 + fallbackText,
1064 + streamClosed: true,
1065 });
1066 + },
1067 + );
1068
1029 - const ensureAssistantTextBlock = (
1030 - context: ClaudeSessionContext,
1031 - blockIndex: number,
1032 - options?: {
1033 - readonly fallbackText?: string;
1034 - readonly streamClosed?: boolean;
1035 - },
1036 - ): Effect.Effect<
1037 - | {
1038 - readonly blockIndex: number;
1039 - readonly block: AssistantTextBlockState;
1040 - }
1041 - | undefined
1042 - > =>
1043 - Effect.gen(function* () {
1044 - const turnState = context.turnState;
1045 - if (!turnState) {
1046 - return undefined;
1047 - }
1069 + const completeAssistantTextBlock = Effect.fn("completeAssistantTextBlock")(function* (
1070 + context: ClaudeSessionContext,
1071 + block: AssistantTextBlockState,
1072 + options?: {
1073 + readonly force?: boolean;
1074 + readonly rawMethod?: string;
1075 + readonly rawPayload?: unknown;
1076 + },
1077 + ) {
1078 + const turnState = context.turnState;
1079 + if (!turnState || block.completionEmitted) {
1080 + return;
1081 + }
1082
1049 - const existing = turnState.assistantTextBlocks.get(blockIndex);
1050 - if (existing && !existing.completionEmitted) {
1051 - if (existing.fallbackText.length === 0 && options?.fallbackText) {
1052 - existing.fallbackText = options.fallbackText;
1053 - }
1054 - if (options?.streamClosed) {
1055 - existing.streamClosed = true;
1056 - }
1057 - return { blockIndex, block: existing };
1058 - }
1083 + if (!options?.force && !block.streamClosed) {
1084 + return;
1085 + }
1086
1060 - const block: AssistantTextBlockState = {
1061 - itemId: yield* Random.nextUUIDv4,
1062 - blockIndex,
1063 - emittedTextDelta: false,
1064 - fallbackText: options?.fallbackText ?? "",
1065 - streamClosed: options?.streamClosed ?? false,
1066 - completionEmitted: false,
1067 - };
1068 - turnState.assistantTextBlocks.set(blockIndex, block);
1069 - turnState.assistantTextBlockOrder.push(block);
1070 - return { blockIndex, block };
1087 + if (!block.emittedTextDelta && block.fallbackText.length > 0) {
1088 + const deltaStamp = yield* makeEventStamp();
1089 + yield* offerRuntimeEvent({
1090 + type: "content.delta",
1091 + eventId: deltaStamp.eventId,
1092 + provider: PROVIDER,
1093 + createdAt: deltaStamp.createdAt,
1094 + threadId: context.session.threadId,
1095 + turnId: turnState.turnId,
1096 + itemId: asRuntimeItemId(block.itemId),
1097 + payload: {
1098 + streamKind: "assistant_text",
1099 + delta: block.fallbackText,
1100 + },
1101 + providerRefs: nativeProviderRefs(context),
1102 + ...(options?.rawMethod || options?.rawPayload
1103 + ? {
1104 + raw: {
1105 + source: "claude.sdk.message" as const,
1106 + ...(options.rawMethod ? { method: options.rawMethod } : {}),
1107 + payload: options?.rawPayload,
1108 + },
1109 + }
1110 + : {}),
1111 });
1112 + }
1113
1073 - const createSyntheticAssistantTextBlock = (
1074 - context: ClaudeSessionContext,
1075 - fallbackText: string,
1076 - ): Effect.Effect<
1077 - | {
1078 - readonly blockIndex: number;
1079 - readonly block: AssistantTextBlockState;
1080 - }
1081 - | undefined
1082 - > =>
1083 - Effect.gen(function* () {
1084 - const turnState = context.turnState;
1085 - if (!turnState) {
1086 - return undefined;
1087 - }
1114 + block.completionEmitted = true;
1115 + if (turnState.assistantTextBlocks.get(block.blockIndex) === block) {
1116 + turnState.assistantTextBlocks.delete(block.blockIndex);
1117 + }
1118 +
1119 + const stamp = yield* makeEventStamp();
1120 + yield* offerRuntimeEvent({
1121 + type: "item.completed",
1122 + eventId: stamp.eventId,
1123 + provider: PROVIDER,
1124 + createdAt: stamp.createdAt,
1125 + itemId: asRuntimeItemId(block.itemId),
1126 + threadId: context.session.threadId,
1127 + turnId: turnState.turnId,
1128 + payload: {
1129 + itemType: "assistant_message",
1130 + status: "completed",
1131 + title: "Assistant message",
1132 + ...(block.fallbackText.length > 0 ? { detail: block.fallbackText } : {}),
1133 + },
1134 + providerRefs: nativeProviderRefs(context),
1135 + ...(options?.rawMethod || options?.rawPayload
1136 + ? {
1137 + raw: {
1138 + source: "claude.sdk.message" as const,
1139 + ...(options.rawMethod ? { method: options.rawMethod } : {}),
1140 + payload: options?.rawPayload,
1141 + },
1142 + }
1143 + : {}),
1144 + });
1145 + });
1146 +
1147 + const backfillAssistantTextBlocksFromSnapshot = Effect.fn(
1148 + "backfillAssistantTextBlocksFromSnapshot",
1149 + )(function* (context: ClaudeSessionContext, message: SDKMessage) {
1150 + const turnState = context.turnState;
1151 + if (!turnState) {
1152 + return;
1153 + }
1154
1089 - const blockIndex = turnState.nextSyntheticAssistantBlockIndex;
1090 - turnState.nextSyntheticAssistantBlockIndex -= 1;
1091 - return yield* ensureAssistantTextBlock(context, blockIndex, {
1092 - fallbackText,
1093 - streamClosed: true,
1155 + const snapshotTextBlocks = extractAssistantTextBlocks(message);
1156 + if (snapshotTextBlocks.length === 0) {
1157 + return;
1158 + }
1159 +
1160 + const orderedBlocks = turnState.assistantTextBlockOrder.map((block) => ({
1161 + blockIndex: block.blockIndex,
1162 + block,
1163 + }));
1164 +
1165 + for (const [position, text] of snapshotTextBlocks.entries()) {
1166 + const existingEntry = orderedBlocks[position];
1167 + const entry =
1168 + existingEntry ??
1169 + (yield* createSyntheticAssistantTextBlock(context, text).pipe(
1170 + Effect.map((created) => {
1171 + if (!created) {
1172 + return undefined;
1173 + }
1174 + orderedBlocks.push(created);
1175 + return created;
1176 + }),
1177 + ));
1178 + if (!entry) {
1179 + continue;
1180 + }
1181 +
1182 + if (entry.block.fallbackText.length === 0) {
1183 + entry.block.fallbackText = text;
1184 + }
1185 +
1186 + if (entry.block.streamClosed && !entry.block.completionEmitted) {
1187 + yield* completeAssistantTextBlock(context, entry.block, {
1188 + rawMethod: "claude/assistant",
1189 + rawPayload: message,
1190 });
1191 + }
1192 + }
1193 + });
1194 +
1195 + const ensureThreadId = Effect.fn("ensureThreadId")(function* (
1196 + context: ClaudeSessionContext,
1197 + message: SDKMessage,
1198 + ) {
1199 + if (typeof message.session_id !== "string" || message.session_id.length === 0) {
1200 + return;
1201 + }
1202 + const nextThreadId = message.session_id;
1203 + context.resumeSessionId = message.session_id;
1204 + yield* updateResumeCursor(context);
1205 +
1206 + if (context.lastThreadStartedId !== nextThreadId) {
1207 + context.lastThreadStartedId = nextThreadId;
1208 + const stamp = yield* makeEventStamp();
1209 + yield* offerRuntimeEvent({
1210 + type: "thread.started",
1211 + eventId: stamp.eventId,
1212 + provider: PROVIDER,
1213 + createdAt: stamp.createdAt,
1214 + threadId: context.session.threadId,
1215 + payload: {
1216 + providerThreadId: nextThreadId,
1217 + },
1218 + providerRefs: {},
1219 + raw: {
1220 + source: "claude.sdk.message",
1221 + method: "claude/thread/started",
1222 + payload: {
1223 + session_id: message.session_id,
1224 + },
1225 + },
1226 });
1227 + }
1228 + });
1229
1097 - const completeAssistantTextBlock = (
1098 - context: ClaudeSessionContext,
1099 - block: AssistantTextBlockState,
1100 - options?: {
1101 - readonly force?: boolean;
1102 - readonly rawMethod?: string;
1103 - readonly rawPayload?: unknown;
1230 + const emitRuntimeError = Effect.fn("emitRuntimeError")(function* (
1231 + context: ClaudeSessionContext,
1232 + message: string,
1233 + cause?: unknown,
1234 + ) {
1235 + if (cause !== undefined) {
1236 + void cause;
1237 + }
1238 + const turnState = context.turnState;
1239 + const stamp = yield* makeEventStamp();
1240 + yield* offerRuntimeEvent({
1241 + type: "runtime.error",
1242 + eventId: stamp.eventId,
1243 + provider: PROVIDER,
1244 + createdAt: stamp.createdAt,
1245 + threadId: context.session.threadId,
1246 + ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}),
1247 + payload: {
1248 + message,
1249 + class: "provider_error",
1250 + ...(cause !== undefined ? { detail: cause } : {}),
1251 },
1105 - ): Effect.Effect<void> =>
1106 - Effect.gen(function* () {
1107 - const turnState = context.turnState;
1108 - if (!turnState || block.completionEmitted) {
1109 - return;
1110 - }
1252 + providerRefs: nativeProviderRefs(context),
1253 + });
1254 + });
1255
1112 - if (!options?.force && !block.streamClosed) {
1113 - return;
1114 - }
1256 + const emitRuntimeWarning = Effect.fn("emitRuntimeWarning")(function* (
1257 + context: ClaudeSessionContext,
1258 + message: string,
1259 + detail?: unknown,
1260 + ) {
1261 + const turnState = context.turnState;
1262 + const stamp = yield* makeEventStamp();
1263 + yield* offerRuntimeEvent({
1264 + type: "runtime.warning",
1265 + eventId: stamp.eventId,
1266 + provider: PROVIDER,
1267 + createdAt: stamp.createdAt,
1268 + threadId: context.session.threadId,
1269 + ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}),
1270 + payload: {
1271 + message,
1272 + ...(detail !== undefined ? { detail } : {}),
1273 + },
1274 + providerRefs: nativeProviderRefs(context),
1275 + });
1276 + });
1277
1116 - if (!block.emittedTextDelta && block.fallbackText.length > 0) {
1117 - const deltaStamp = yield* makeEventStamp();
1118 - yield* offerRuntimeEvent({
1119 - type: "content.delta",
1120 - eventId: deltaStamp.eventId,
1121 - provider: PROVIDER,
1122 - createdAt: deltaStamp.createdAt,
1123 - threadId: context.session.threadId,
1124 - turnId: turnState.turnId,
1125 - itemId: asRuntimeItemId(block.itemId),
1126 - payload: {
1127 - streamKind: "assistant_text",
1128 - delta: block.fallbackText,
1129 - },
1130 - providerRefs: nativeProviderRefs(context),
1131 - ...(options?.rawMethod || options?.rawPayload
1132 - ? {
1133 - raw: {
1134 - source: "claude.sdk.message" as const,
1135 - ...(options.rawMethod ? { method: options.rawMethod } : {}),
1136 - payload: options?.rawPayload,
1137 - },
1138 - }
1139 - : {}),
1140 - });
1141 - }
1278 + const emitProposedPlanCompleted = Effect.fn("emitProposedPlanCompleted")(function* (
1279 + context: ClaudeSessionContext,
1280 + input: {
1281 + readonly planMarkdown: string;
1282 + readonly toolUseId?: string | undefined;
1283 + readonly rawSource: "claude.sdk.message" | "claude.sdk.permission";
1284 + readonly rawMethod: string;
1285 + readonly rawPayload: unknown;
1286 + },
1287 + ) {
1288 + const turnState = context.turnState;
1289 + const planMarkdown = input.planMarkdown.trim();
1290 + if (!turnState || planMarkdown.length === 0) {
1291 + return;
1292 + }
1293 +
1294 + const captureKey = exitPlanCaptureKey({
1295 + toolUseId: input.toolUseId,
1296 + planMarkdown,
1297 + });
1298 + if (turnState.capturedProposedPlanKeys.has(captureKey)) {
1299 + return;
1300 + }
1301 + turnState.capturedProposedPlanKeys.add(captureKey);
1302 +
1303 + const stamp = yield* makeEventStamp();
1304 + yield* offerRuntimeEvent({
1305 + type: "turn.proposed.completed",
1306 + eventId: stamp.eventId,
1307 + provider: PROVIDER,
1308 + createdAt: stamp.createdAt,
1309 + threadId: context.session.threadId,
1310 + turnId: turnState.turnId,
1311 + payload: {
1312 + planMarkdown,
1313 + },
1314 + providerRefs: nativeProviderRefs(context, {
1315 + providerItemId: input.toolUseId,
1316 + }),
1317 + raw: {
1318 + source: input.rawSource,
1319 + method: input.rawMethod,
1320 + payload: input.rawPayload,
1321 + },
1322 + });
1323 + });
1324 +
1325 + const completeTurn = Effect.fn("completeTurn")(function* (
1326 + context: ClaudeSessionContext,
1327 + status: ProviderRuntimeTurnStatus,
1328 + errorMessage?: string,
1329 + result?: SDKResultMessage,
1330 + ) {
1331 + const resultUsage =
1332 + result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined;
1333 + const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);
1334 + if (resultContextWindow !== undefined) {
1335 + context.lastKnownContextWindow = resultContextWindow;
1336 + }
1337
1143 - block.completionEmitted = true;
1144 - if (turnState.assistantTextBlocks.get(block.blockIndex) === block) {
1145 - turnState.assistantTextBlocks.delete(block.blockIndex);
1338 + // The SDK result.usage contains *accumulated* totals across all API calls
1339 + // (input_tokens, cache_read_input_tokens, etc. summed over every request).
1340 + // This does NOT represent the current context window size.
1341 + // Instead, use the last known context-window-accurate usage from task_progress
1342 + // events and treat the accumulated total as totalProcessedTokens.
1343 + const accumulatedSnapshot = normalizeClaudeTokenUsage(
1344 + resultUsage,
1345 + resultContextWindow ?? context.lastKnownContextWindow,
1346 + );
1347 + const lastGoodUsage = context.lastKnownTokenUsage;
1348 + const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
1349 + const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
1350 + ? {
1351 + ...lastGoodUsage,
1352 + ...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
1353 + ? { maxTokens }
1354 + : {}),
1355 + ...(accumulatedSnapshot && accumulatedSnapshot.usedTokens > lastGoodUsage.usedTokens
1356 + ? { totalProcessedTokens: accumulatedSnapshot.usedTokens }
1357 + : {}),
1358 }
1359 + : accumulatedSnapshot;
1360
1148 - const stamp = yield* makeEventStamp();
1361 + const turnState = context.turnState;
1362 + if (!turnState) {
1363 + if (usageSnapshot) {
1364 + const usageStamp = yield* makeEventStamp();
1365 yield* offerRuntimeEvent({
1150 - type: "item.completed",
1151 - eventId: stamp.eventId,
1366 + type: "thread.token-usage.updated",
1367 + eventId: usageStamp.eventId,
1368 provider: PROVIDER,
1153 - createdAt: stamp.createdAt,
1154 - itemId: asRuntimeItemId(block.itemId),
1369 + createdAt: usageStamp.createdAt,
1370 threadId: context.session.threadId,
1156 - turnId: turnState.turnId,
1371 payload: {
1158 - itemType: "assistant_message",
1159 - status: "completed",
1160 - title: "Assistant message",
1161 - ...(block.fallbackText.length > 0 ? { detail: block.fallbackText } : {}),
1372 + usage: usageSnapshot,
1373 },
1163 - providerRefs: nativeProviderRefs(context),
1164 - ...(options?.rawMethod || options?.rawPayload
1165 - ? {
1166 - raw: {
1167 - source: "claude.sdk.message" as const,
1168 - ...(options.rawMethod ? { method: options.rawMethod } : {}),
1169 - payload: options?.rawPayload,
1170 - },
1171 - }
1172 - : {}),
1374 + providerRefs: {},
1375 });
1376 + }
1377 +
1378 + const stamp = yield* makeEventStamp();
1379 + yield* offerRuntimeEvent({
1380 + type: "turn.completed",
1381 + eventId: stamp.eventId,
1382 + provider: PROVIDER,
1383 + createdAt: stamp.createdAt,
1384 + threadId: context.session.threadId,
1385 + payload: {
1386 + state: status,
1387 + ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),
1388 + ...(result?.usage ? { usage: result.usage } : {}),
1389 + ...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),
1390 + ...(typeof result?.total_cost_usd === "number"
1391 + ? { totalCostUsd: result.total_cost_usd }
1392 + : {}),
1393 + ...(errorMessage ? { errorMessage } : {}),
1394 + },
1395 + providerRefs: {},
1396 });
1397 + return;
1398 + }
1399
1176 - const backfillAssistantTextBlocksFromSnapshot = (
1177 - context: ClaudeSessionContext,
1178 - message: SDKMessage,
1179 - ): Effect.Effect<void> =>
1180 - Effect.gen(function* () {
1181 - const turnState = context.turnState;
1182 - if (!turnState) {
1183 - return;
1184 - }
1400 + for (const [index, tool] of context.inFlightTools.entries()) {
1401 + const toolStamp = yield* makeEventStamp();
1402 + yield* offerRuntimeEvent({
1403 + type: "item.completed",
1404 + eventId: toolStamp.eventId,
1405 + provider: PROVIDER,
1406 + createdAt: toolStamp.createdAt,
1407 + threadId: context.session.threadId,
1408 + turnId: turnState.turnId,
1409 + itemId: asRuntimeItemId(tool.itemId),
1410 + payload: {
1411 + itemType: tool.itemType,
1412 + status: status === "completed" ? "completed" : "failed",
1413 + title: tool.title,
1414 + ...(tool.detail ? { detail: tool.detail } : {}),
1415 + data: {
1416 + toolName: tool.toolName,
1417 + input: tool.input,
1418 + },
1419 + },
1420 + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
1421 + raw: {
1422 + source: "claude.sdk.message",
1423 + method: "claude/result",
1424 + payload: result ?? { status },
1425 + },
1426 + });
1427 + context.inFlightTools.delete(index);
1428 + }
1429 + // Clear any remaining stale entries (e.g. from interrupted content blocks)
1430 + context.inFlightTools.clear();
1431 +
1432 + for (const block of turnState.assistantTextBlockOrder) {
1433 + yield* completeAssistantTextBlock(context, block, {
1434 + force: true,
1435 + rawMethod: "claude/result",
1436 + rawPayload: result ?? { status },
1437 + });
1438 + }
1439
1186 - const snapshotTextBlocks = extractAssistantTextBlocks(message);
1187 - if (snapshotTextBlocks.length === 0) {
1188 - return;
1189 - }
1440 + context.turns.push({
1441 + id: turnState.turnId,
1442 + items: [...turnState.items],
1443 + });
1444
1191 - const orderedBlocks = turnState.assistantTextBlockOrder.map((block) => ({
1192 - blockIndex: block.blockIndex,
1193 - block,
1194 - }));
1195 -
1196 - for (const [position, text] of snapshotTextBlocks.entries()) {
1197 - const existingEntry = orderedBlocks[position];
1198 - const entry =
1199 - existingEntry ??
1200 - (yield* createSyntheticAssistantTextBlock(context, text).pipe(
1201 - Effect.map((created) => {
1202 - if (!created) {
1203 - return undefined;
1204 - }
1205 - orderedBlocks.push(created);
1206 - return created;
1207 - }),
1208 - ));
1209 - if (!entry) {
1210 - continue;
1211 - }
1445 + if (usageSnapshot) {
1446 + const usageStamp = yield* makeEventStamp();
1447 + yield* offerRuntimeEvent({
1448 + type: "thread.token-usage.updated",
1449 + eventId: usageStamp.eventId,
1450 + provider: PROVIDER,
1451 + createdAt: usageStamp.createdAt,
1452 + threadId: context.session.threadId,
1453 + turnId: turnState.turnId,
1454 + payload: {
1455 + usage: usageSnapshot,
1456 + },
1457 + providerRefs: nativeProviderRefs(context),
1458 + });
1459 + }
1460
1213 - if (entry.block.fallbackText.length === 0) {
1214 - entry.block.fallbackText = text;
1215 - }
1461 + const stamp = yield* makeEventStamp();
1462 + yield* offerRuntimeEvent({
1463 + type: "turn.completed",
1464 + eventId: stamp.eventId,
1465 + provider: PROVIDER,
1466 + createdAt: stamp.createdAt,
1467 + threadId: context.session.threadId,
1468 + turnId: turnState.turnId,
1469 + payload: {
1470 + state: status,
1471 + ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),
1472 + ...(result?.usage ? { usage: result.usage } : {}),
1473 + ...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),
1474 + ...(typeof result?.total_cost_usd === "number"
1475 + ? { totalCostUsd: result.total_cost_usd }
1476 + : {}),
1477 + ...(errorMessage ? { errorMessage } : {}),
1478 + },
1479 + providerRefs: nativeProviderRefs(context),
1480 + });
1481
1217 - if (entry.block.streamClosed && !entry.block.completionEmitted) {
1218 - yield* completeAssistantTextBlock(context, entry.block, {
1219 - rawMethod: "claude/assistant",
1220 - rawPayload: message,
1221 - });
1222 - }
1223 - }
1224 - });
1482 + const updatedAt = yield* nowIso;
1483 + context.turnState = undefined;
1484 + context.session = {
1485 + ...context.session,
1486 + status: "ready",
1487 + activeTurnId: undefined,
1488 + updatedAt,
1489 + ...(status === "failed" && errorMessage ? { lastError: errorMessage } : {}),
1490 + };
1491 + yield* updateResumeCursor(context);
1492 + });
1493 +
1494 + const handleStreamEvent = Effect.fn("handleStreamEvent")(function* (
1495 + context: ClaudeSessionContext,
1496 + message: SDKMessage,
1497 + ) {
1498 + if (message.type !== "stream_event") {
1499 + return;
1500 + }
1501
1226 - const ensureThreadId = (
1227 - context: ClaudeSessionContext,
1228 - message: SDKMessage,
1229 - ): Effect.Effect<void> =>
1230 - Effect.gen(function* () {
1231 - if (typeof message.session_id !== "string" || message.session_id.length === 0) {
1502 + const { event } = message;
1503 +
1504 + if (event.type === "content_block_delta") {
1505 + if (
1506 + (event.delta.type === "text_delta" || event.delta.type === "thinking_delta") &&
1507 + context.turnState
1508 + ) {
1509 + const deltaText =
1510 + event.delta.type === "text_delta"
1511 + ? event.delta.text
1512 + : typeof event.delta.thinking === "string"
1513 + ? event.delta.thinking
1514 + : "";
1515 + if (deltaText.length === 0) {
1516 return;
1517 }
1234 - const nextThreadId = message.session_id;
1235 - context.resumeSessionId = message.session_id;
1236 - yield* updateResumeCursor(context);
1237 -
1238 - if (context.lastThreadStartedId !== nextThreadId) {
1239 - context.lastThreadStartedId = nextThreadId;
1240 - const stamp = yield* makeEventStamp();
1241 - yield* offerRuntimeEvent({
1242 - type: "thread.started",
1243 - eventId: stamp.eventId,
1244 - provider: PROVIDER,
1245 - createdAt: stamp.createdAt,
1246 - threadId: context.session.threadId,
1247 - payload: {
1248 - providerThreadId: nextThreadId,
1249 - },
1250 - providerRefs: {},
1251 - raw: {
1252 - source: "claude.sdk.message",
1253 - method: "claude/thread/started",
1254 - payload: {
1255 - session_id: message.session_id,
1256 - },
1257 - },
1258 - });
1259 - }
1260 - });
1261 -
1262 - const emitRuntimeError = (
1263 - context: ClaudeSessionContext,
1264 - message: string,
1265 - cause?: unknown,
1266 - ): Effect.Effect<void> =>
1267 - Effect.gen(function* () {
1268 - if (cause !== undefined) {
1269 - void cause;
1518 + const streamKind = streamKindFromDeltaType(event.delta.type);
1519 + const assistantBlockEntry =
1520 + event.delta.type === "text_delta"
1521 + ? yield* ensureAssistantTextBlock(context, event.index)
1522 + : context.turnState.assistantTextBlocks.get(event.index)
1523 + ? {
1524 + blockIndex: event.index,
1525 + block: context.turnState.assistantTextBlocks.get(
1526 + event.index,
1527 + ) as AssistantTextBlockState,
1528 + }
1529 + : undefined;
1530 + if (assistantBlockEntry?.block && event.delta.type === "text_delta") {
1531 + assistantBlockEntry.block.emittedTextDelta = true;
1532 }
1271 - const turnState = context.turnState;
1533 const stamp = yield* makeEventStamp();
1534 yield* offerRuntimeEvent({
1274 - type: "runtime.error",
1535 + type: "content.delta",
1536 eventId: stamp.eventId,
1537 provider: PROVIDER,
1538 createdAt: stamp.createdAt,
1539 threadId: context.session.threadId,
1279 - ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}),
1540 + turnId: context.turnState.turnId,
1541 + ...(assistantBlockEntry?.block
1542 + ? { itemId: asRuntimeItemId(assistantBlockEntry.block.itemId) }
1543 + : {}),
1544 payload: {
1281 - message,
1282 - class: "provider_error",
1283 - ...(cause !== undefined ? { detail: cause } : {}),
1545 + streamKind,
1546 + delta: deltaText,
1547 },
1548 providerRefs: nativeProviderRefs(context),
1286 - });
1287 - });
1288 -
1289 - const emitRuntimeWarning = (
1290 - context: ClaudeSessionContext,
1291 - message: string,
1292 - detail?: unknown,
1293 - ): Effect.Effect<void> =>
1294 - Effect.gen(function* () {
1295 - const turnState = context.turnState;
1296 - const stamp = yield* makeEventStamp();
1297 - yield* offerRuntimeEvent({
1298 - type: "runtime.warning",
1299 - eventId: stamp.eventId,
1300 - provider: PROVIDER,
1301 - createdAt: stamp.createdAt,
1302 - threadId: context.session.threadId,
1303 - ...(turnState ? { turnId: asCanonicalTurnId(turnState.turnId) } : {}),
1304 - payload: {
1305 - message,
1306 - ...(detail !== undefined ? { detail } : {}),
1549 + raw: {
1550 + source: "claude.sdk.message",
1551 + method: "claude/stream_event/content_block_delta",
1552 + payload: message,
1553 },
1308 - providerRefs: nativeProviderRefs(context),
1554 });
1310 - });
1555 + return;
1556 + }
1557
1312 - const emitProposedPlanCompleted = (
1313 - context: ClaudeSessionContext,
1314 - input: {
1315 - readonly planMarkdown: string;
1316 - readonly toolUseId?: string | undefined;
1317 - readonly rawSource: "claude.sdk.message" | "claude.sdk.permission";
1318 - readonly rawMethod: string;
1319 - readonly rawPayload: unknown;
1320 - },
1321 - ): Effect.Effect<void> =>
1322 - Effect.gen(function* () {
1323 - const turnState = context.turnState;
1324 - const planMarkdown = input.planMarkdown.trim();
1325 - if (!turnState || planMarkdown.length === 0) {
1558 + if (event.delta.type === "input_json_delta") {
1559 + const tool = context.inFlightTools.get(event.index);
1560 + if (!tool || typeof event.delta.partial_json !== "string") {
1561 return;
1562 }
1563
1329 - const captureKey = exitPlanCaptureKey({
1330 - toolUseId: input.toolUseId,
1331 - planMarkdown,
1332 - });
1333 - if (turnState.capturedProposedPlanKeys.has(captureKey)) {
1564 + const partialInputJson = tool.partialInputJson + event.delta.partial_json;
1565 + const parsedInput = tryParseJsonRecord(partialInputJson);
1566 + const detail = parsedInput ? summarizeToolRequest(tool.toolName, parsedInput) : tool.detail;
1567 + let nextTool: ToolInFlight = {
1568 + ...tool,
1569 + partialInputJson,
1570 + ...(parsedInput ? { input: parsedInput } : {}),
1571 + ...(detail ? { detail } : {}),
1572 + };
1573 +
1574 + const nextFingerprint =
1575 + parsedInput && Object.keys(parsedInput).length > 0
1576 + ? toolInputFingerprint(parsedInput)
1577 + : undefined;
1578 + context.inFlightTools.set(event.index, nextTool);
1579 +
1580 + if (
1581 + !parsedInput ||
1582 + !nextFingerprint ||
1583 + tool.lastEmittedInputFingerprint === nextFingerprint
1584 + ) {
1585 return;
1586 }
1336 - turnState.capturedProposedPlanKeys.add(captureKey);
1587 +
1588 + nextTool = {
1589 + ...nextTool,
1590 + lastEmittedInputFingerprint: nextFingerprint,
1591 + };
1592 + context.inFlightTools.set(event.index, nextTool);
1593
1594 const stamp = yield* makeEventStamp();
1595 yield* offerRuntimeEvent({
1340 - type: "turn.proposed.completed",
1596 + type: "item.updated",
1597 eventId: stamp.eventId,
1598 provider: PROVIDER,
1599 createdAt: stamp.createdAt,
1600 threadId: context.session.threadId,
1345 - turnId: turnState.turnId,
1601 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
1602 + itemId: asRuntimeItemId(nextTool.itemId),
1603 payload: {
1347 - planMarkdown,
1604 + itemType: nextTool.itemType,
1605 + status: "inProgress",
1606 + title: nextTool.title,
1607 + ...(nextTool.detail ? { detail: nextTool.detail } : {}),
1608 + data: {
1609 + toolName: nextTool.toolName,
1610 + input: nextTool.input,
1611 + },
1612 },
1349 - providerRefs: nativeProviderRefs(context, {
1350 - providerItemId: input.toolUseId,
1351 - }),
1613 + providerRefs: nativeProviderRefs(context, { providerItemId: nextTool.itemId }),
1614 raw: {
1353 - source: input.rawSource,
1354 - method: input.rawMethod,
1355 - payload: input.rawPayload,
1615 + source: "claude.sdk.message",
1616 + method: "claude/stream_event/content_block_delta/input_json_delta",
1617 + payload: message,
1618 },
1619 });
1358 - });
1620 + }
1621 + return;
1622 + }
1623
1360 - const completeTurn = (
1361 - context: ClaudeSessionContext,
1362 - status: ProviderRuntimeTurnStatus,
1363 - errorMessage?: string,
1364 - result?: SDKResultMessage,
1365 - ): Effect.Effect<void> =>
1366 - Effect.gen(function* () {
1367 - const resultUsage =
1368 - result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined;
1369 - const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);
1370 - if (resultContextWindow !== undefined) {
1371 - context.lastKnownContextWindow = resultContextWindow;
1372 - }
1624 + if (event.type === "content_block_start") {
1625 + const { index, content_block: block } = event;
1626 + if (block.type === "text") {
1627 + yield* ensureAssistantTextBlock(context, index, {
1628 + fallbackText: extractContentBlockText(block),
1629 + });
1630 + return;
1631 + }
1632 + if (
1633 + block.type !== "tool_use" &&
1634 + block.type !== "server_tool_use" &&
1635 + block.type !== "mcp_tool_use"
1636 + ) {
1637 + return;
1638 + }
1639
1374 - // The SDK result.usage contains *accumulated* totals across all API calls
1375 - // (input_tokens, cache_read_input_tokens, etc. summed over every request).
1376 - // This does NOT represent the current context window size.
1377 - // Instead, use the last known context-window-accurate usage from task_progress
1378 - // events and treat the accumulated total as totalProcessedTokens.
1379 - const accumulatedSnapshot = normalizeClaudeTokenUsage(
1380 - resultUsage,
1381 - resultContextWindow ?? context.lastKnownContextWindow,
1382 - );
1383 - const lastGoodUsage = context.lastKnownTokenUsage;
1384 - const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
1385 - const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
1386 - ? {
1387 - ...lastGoodUsage,
1388 - ...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
1389 - ? { maxTokens }
1390 - : {}),
1391 - ...(accumulatedSnapshot && accumulatedSnapshot.usedTokens > lastGoodUsage.usedTokens
1392 - ? { totalProcessedTokens: accumulatedSnapshot.usedTokens }
1393 - : {}),
1394 - }
1395 - : accumulatedSnapshot;
1640 + const toolName = block.name;
1641 + const itemType = classifyToolItemType(toolName);
1642 + const toolInput =
1643 + typeof block.input === "object" && block.input !== null
1644 + ? (block.input as Record<string, unknown>)
1645 + : {};
1646 + const itemId = block.id;
1647 + const detail = summarizeToolRequest(toolName, toolInput);
1648 + const inputFingerprint =
1649 + Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined;
1650 +
1651 + const tool: ToolInFlight = {
1652 + itemId,
1653 + itemType,
1654 + toolName,
1655 + title: titleForTool(itemType),
1656 + detail,
1657 + input: toolInput,
1658 + partialInputJson: "",
1659 + ...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}),
1660 + };
1661 + context.inFlightTools.set(index, tool);
1662 +
1663 + const stamp = yield* makeEventStamp();
1664 + yield* offerRuntimeEvent({
1665 + type: "item.started",
1666 + eventId: stamp.eventId,
1667 + provider: PROVIDER,
1668 + createdAt: stamp.createdAt,
1669 + threadId: context.session.threadId,
1670 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
1671 + itemId: asRuntimeItemId(tool.itemId),
1672 + payload: {
1673 + itemType: tool.itemType,
1674 + status: "inProgress",
1675 + title: tool.title,
1676 + ...(tool.detail ? { detail: tool.detail } : {}),
1677 + data: {
1678 + toolName: tool.toolName,
1679 + input: toolInput,
1680 + },
1681 + },
1682 + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
1683 + raw: {
1684 + source: "claude.sdk.message",
1685 + method: "claude/stream_event/content_block_start",
1686 + payload: message,
1687 + },
1688 + });
1689 + return;
1690 + }
1691
1397 - const turnState = context.turnState;
1398 - if (!turnState) {
1399 - if (usageSnapshot) {
1400 - const usageStamp = yield* makeEventStamp();
1401 - yield* offerRuntimeEvent({
1402 - type: "thread.token-usage.updated",
1403 - eventId: usageStamp.eventId,
1404 - provider: PROVIDER,
1405 - createdAt: usageStamp.createdAt,
1406 - threadId: context.session.threadId,
1407 - payload: {
1408 - usage: usageSnapshot,
1409 - },
1410 - providerRefs: {},
1411 - });
1412 - }
1692 + if (event.type === "content_block_stop") {
1693 + const { index } = event;
1694 + const assistantBlock = context.turnState?.assistantTextBlocks.get(index);
1695 + if (assistantBlock) {
1696 + assistantBlock.streamClosed = true;
1697 + yield* completeAssistantTextBlock(context, assistantBlock, {
1698 + rawMethod: "claude/stream_event/content_block_stop",
1699 + rawPayload: message,
1700 + });
1701 + return;
1702 + }
1703 + const tool = context.inFlightTools.get(index);
1704 + if (!tool) {
1705 + return;
1706 + }
1707 + }
1708 + });
1709
1414 - const stamp = yield* makeEventStamp();
1415 - yield* offerRuntimeEvent({
1416 - type: "turn.completed",
1417 - eventId: stamp.eventId,
1418 - provider: PROVIDER,
1419 - createdAt: stamp.createdAt,
1420 - threadId: context.session.threadId,
1421 - payload: {
1422 - state: status,
1423 - ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),
1424 - ...(result?.usage ? { usage: result.usage } : {}),
1425 - ...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),
1426 - ...(typeof result?.total_cost_usd === "number"
1427 - ? { totalCostUsd: result.total_cost_usd }
1428 - : {}),
1429 - ...(errorMessage ? { errorMessage } : {}),
1430 - },
1431 - providerRefs: {},
1432 - });
1433 - return;
1434 - }
1710 + const handleUserMessage = Effect.fn("handleUserMessage")(function* (
1711 + context: ClaudeSessionContext,
1712 + message: SDKMessage,
1713 + ) {
1714 + if (message.type !== "user") {
1715 + return;
1716 + }
1717
1436 - for (const [index, tool] of context.inFlightTools.entries()) {
1437 - const toolStamp = yield* makeEventStamp();
1438 - yield* offerRuntimeEvent({
1439 - type: "item.completed",
1440 - eventId: toolStamp.eventId,
1441 - provider: PROVIDER,
1442 - createdAt: toolStamp.createdAt,
1443 - threadId: context.session.threadId,
1444 - turnId: turnState.turnId,
1445 - itemId: asRuntimeItemId(tool.itemId),
1446 - payload: {
1447 - itemType: tool.itemType,
1448 - status: status === "completed" ? "completed" : "failed",
1449 - title: tool.title,
1450 - ...(tool.detail ? { detail: tool.detail } : {}),
1451 - data: {
1452 - toolName: tool.toolName,
1453 - input: tool.input,
1454 - },
1455 - },
1456 - providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
1457 - raw: {
1458 - source: "claude.sdk.message",
1459 - method: "claude/result",
1460 - payload: result ?? { status },
1461 - },
1462 - });
1463 - context.inFlightTools.delete(index);
1464 - }
1465 - // Clear any remaining stale entries (e.g. from interrupted content blocks)
1466 - context.inFlightTools.clear();
1467 -
1468 - for (const block of turnState.assistantTextBlockOrder) {
1469 - yield* completeAssistantTextBlock(context, block, {
1470 - force: true,
1471 - rawMethod: "claude/result",
1472 - rawPayload: result ?? { status },
1473 - });
1474 - }
1718 + if (context.turnState) {
1719 + context.turnState.items.push(message.message);
1720 + }
1721
1476 - context.turns.push({
1477 - id: turnState.turnId,
1478 - items: [...turnState.items],
1479 - });
1722 + for (const toolResult of toolResultBlocksFromUserMessage(message)) {
1723 + const toolEntry = Array.from(context.inFlightTools.entries()).find(
1724 + ([, tool]) => tool.itemId === toolResult.toolUseId,
1725 + );
1726 + if (!toolEntry) {
1727 + continue;
1728 + }
1729
1481 - if (usageSnapshot) {
1482 - const usageStamp = yield* makeEventStamp();
1483 - yield* offerRuntimeEvent({
1484 - type: "thread.token-usage.updated",
1485 - eventId: usageStamp.eventId,
1486 - provider: PROVIDER,
1487 - createdAt: usageStamp.createdAt,
1488 - threadId: context.session.threadId,
1489 - turnId: turnState.turnId,
1490 - payload: {
1491 - usage: usageSnapshot,
1492 - },
1493 - providerRefs: nativeProviderRefs(context),
1494 - });
1495 - }
1730 + const [index, tool] = toolEntry;
1731 + const itemStatus = toolResult.isError ? "failed" : "completed";
1732 + const toolData = {
1733 + toolName: tool.toolName,
1734 + input: tool.input,
1735 + result: toolResult.block,
1736 + };
1737 +
1738 + const updatedStamp = yield* makeEventStamp();
1739 + yield* offerRuntimeEvent({
1740 + type: "item.updated",
1741 + eventId: updatedStamp.eventId,
1742 + provider: PROVIDER,
1743 + createdAt: updatedStamp.createdAt,
1744 + threadId: context.session.threadId,
1745 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
1746 + itemId: asRuntimeItemId(tool.itemId),
1747 + payload: {
1748 + itemType: tool.itemType,
1749 + status: toolResult.isError ? "failed" : "inProgress",
1750 + title: tool.title,
1751 + ...(tool.detail ? { detail: tool.detail } : {}),
1752 + data: toolData,
1753 + },
1754 + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
1755 + raw: {
1756 + source: "claude.sdk.message",
1757 + method: "claude/user",
1758 + payload: message,
1759 + },
1760 + });
1761
1497 - const stamp = yield* makeEventStamp();
1762 + const streamKind = toolResultStreamKind(tool.itemType);
1763 + if (streamKind && toolResult.text.length > 0 && context.turnState) {
1764 + const deltaStamp = yield* makeEventStamp();
1765 yield* offerRuntimeEvent({
1499 - type: "turn.completed",
1500 - eventId: stamp.eventId,
1766 + type: "content.delta",
1767 + eventId: deltaStamp.eventId,
1768 provider: PROVIDER,
1502 - createdAt: stamp.createdAt,
1769 + createdAt: deltaStamp.createdAt,
1770 threadId: context.session.threadId,
1504 - turnId: turnState.turnId,
1771 + turnId: context.turnState.turnId,
1772 + itemId: asRuntimeItemId(tool.itemId),
1773 payload: {
1506 - state: status,
1507 - ...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),
1508 - ...(result?.usage ? { usage: result.usage } : {}),
1509 - ...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),
1510 - ...(typeof result?.total_cost_usd === "number"
1511 - ? { totalCostUsd: result.total_cost_usd }
1512 - : {}),
1513 - ...(errorMessage ? { errorMessage } : {}),
1774 + streamKind,
1775 + delta: toolResult.text,
1776 + },
1777 + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
1778 + raw: {
1779 + source: "claude.sdk.message",
1780 + method: "claude/user",
1781 + payload: message,
1782 },
1515 - providerRefs: nativeProviderRefs(context),
1783 });
1784 + }
1785
1518 - const updatedAt = yield* nowIso;
1519 - context.turnState = undefined;
1520 - context.session = {
1521 - ...context.session,
1522 - status: "ready",
1523 - activeTurnId: undefined,
1524 - updatedAt,
1525 - ...(status === "failed" && errorMessage ? { lastError: errorMessage } : {}),
1526 - };
1527 - yield* updateResumeCursor(context);
1786 + const completedStamp = yield* makeEventStamp();
1787 + yield* offerRuntimeEvent({
1788 + type: "item.completed",
1789 + eventId: completedStamp.eventId,
1790 + provider: PROVIDER,
1791 + createdAt: completedStamp.createdAt,
1792 + threadId: context.session.threadId,
1793 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
1794 + itemId: asRuntimeItemId(tool.itemId),
1795 + payload: {
1796 + itemType: tool.itemType,
1797 + status: itemStatus,
1798 + title: tool.title,
1799 + ...(tool.detail ? { detail: tool.detail } : {}),
1800 + data: toolData,
1801 + },
1802 + providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
1803 + raw: {
1804 + source: "claude.sdk.message",
1805 + method: "claude/user",
1806 + payload: message,
1807 + },
1808 });
1809
1530 - const handleStreamEvent = (
1531 - context: ClaudeSessionContext,
1532 - message: SDKMessage,
1533 - ): Effect.Effect<void> =>
1534 - Effect.gen(function* () {
1535 - if (message.type !== "stream_event") {
1536 - return;
1537 - }
1538 -
1539 - const { event } = message;
1540 -
1541 - if (event.type === "content_block_delta") {
1542 - if (
1543 - (event.delta.type === "text_delta" || event.delta.type === "thinking_delta") &&
1544 - context.turnState
1545 - ) {
1546 - const deltaText =
1547 - event.delta.type === "text_delta"
1548 - ? event.delta.text
1549 - : typeof event.delta.thinking === "string"
1550 - ? event.delta.thinking
1551 - : "";
1552 - if (deltaText.length === 0) {
1553 - return;
1554 - }
1555 - const streamKind = streamKindFromDeltaType(event.delta.type);
1556 - const assistantBlockEntry =
1557 - event.delta.type === "text_delta"
1558 - ? yield* ensureAssistantTextBlock(context, event.index)
1559 - : context.turnState.assistantTextBlocks.get(event.index)
1560 - ? {
1561 - blockIndex: event.index,
1562 - block: context.turnState.assistantTextBlocks.get(
1563 - event.index,
1564 - ) as AssistantTextBlockState,
1565 - }
1566 - : undefined;
1567 - if (assistantBlockEntry?.block && event.delta.type === "text_delta") {
1568 - assistantBlockEntry.block.emittedTextDelta = true;
1569 - }
1570 - const stamp = yield* makeEventStamp();
1571 - yield* offerRuntimeEvent({
1572 - type: "content.delta",
1573 - eventId: stamp.eventId,
1574 - provider: PROVIDER,
1575 - createdAt: stamp.createdAt,
1576 - threadId: context.session.threadId,
1577 - turnId: context.turnState.turnId,
1578 - ...(assistantBlockEntry?.block
1579 - ? { itemId: asRuntimeItemId(assistantBlockEntry.block.itemId) }
1580 - : {}),
1581 - payload: {
1582 - streamKind,
1583 - delta: deltaText,
1584 - },
1585 - providerRefs: nativeProviderRefs(context),
1586 - raw: {
1587 - source: "claude.sdk.message",
1588 - method: "claude/stream_event/content_block_delta",
1589 - payload: message,
1590 - },
1591 - });
1592 - return;
1593 - }
1594 -
1595 - if (event.delta.type === "input_json_delta") {
1596 - const tool = context.inFlightTools.get(event.index);
1597 - if (!tool || typeof event.delta.partial_json !== "string") {
1598 - return;
1599 - }
1600 -
1601 - const partialInputJson = tool.partialInputJson + event.delta.partial_json;
1602 - const parsedInput = tryParseJsonRecord(partialInputJson);
1603 - const detail = parsedInput
1604 - ? summarizeToolRequest(tool.toolName, parsedInput)
1605 - : tool.detail;
1606 - let nextTool: ToolInFlight = {
1607 - ...tool,
1608 - partialInputJson,
1609 - ...(parsedInput ? { input: parsedInput } : {}),
1610 - ...(detail ? { detail } : {}),
1611 - };
1612 -
1613 - const nextFingerprint =
1614 - parsedInput && Object.keys(parsedInput).length > 0
1615 - ? toolInputFingerprint(parsedInput)
1616 - : undefined;
1617 - context.inFlightTools.set(event.index, nextTool);
1618 -
1619 - if (
1620 - !parsedInput ||
1621 - !nextFingerprint ||
1622 - tool.lastEmittedInputFingerprint === nextFingerprint
1623 - ) {
1624 - return;
1625 - }
1626 -
1627 - nextTool = {
1628 - ...nextTool,
1629 - lastEmittedInputFingerprint: nextFingerprint,
1630 - };
1631 - context.inFlightTools.set(event.index, nextTool);
1632 -
1633 - const stamp = yield* makeEventStamp();
1634 - yield* offerRuntimeEvent({
1635 - type: "item.updated",
1636 - eventId: stamp.eventId,
1637 - provider: PROVIDER,
1638 - createdAt: stamp.createdAt,
1639 - threadId: context.session.threadId,
1640 - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
1641 - itemId: asRuntimeItemId(nextTool.itemId),
1642 - payload: {
1643 - itemType: nextTool.itemType,
1644 - status: "inProgress",
1645 - title: nextTool.title,
1646 - ...(nextTool.detail ? { detail: nextTool.detail } : {}),
1647 - data: {
1648 - toolName: nextTool.toolName,
1649 - input: nextTool.input,
1650 - },
1651 - },
1652 - providerRefs: nativeProviderRefs(context, { providerItemId: nextTool.itemId }),
1653 - raw: {
1654 - source: "claude.sdk.message",
1655 - method: "claude/stream_event/content_block_delta/input_json_delta",
1656 - payload: message,
1657 - },
1658 - });
1659 - }
1660 - return;
1661 - }
1662 -
1663 - if (event.type === "content_block_start") {
1664 - const { index, content_block: block } = event;
1665 - if (block.type === "text") {
1666 - yield* ensureAssistantTextBlock(context, index, {
1667 - fallbackText: extractContentBlockText(block),
1668 - });
1669 - return;
1670 - }
1671 - if (
1672 - block.type !== "tool_use" &&
1673 - block.type !== "server_tool_use" &&
1674 - block.type !== "mcp_tool_use"
1675 - ) {
1676 - return;
1677 - }
1810 + context.inFlightTools.delete(index);
1811 + }
1812 + });
1813
1679 - const toolName = block.name;
1680 - const itemType = classifyToolItemType(toolName);
1681 - const toolInput =
1682 - typeof block.input === "object" && block.input !== null
1683 - ? (block.input as Record<string, unknown>)
1684 - : {};
1685 - const itemId = block.id;
1686 - const detail = summarizeToolRequest(toolName, toolInput);
1687 - const inputFingerprint =
1688 - Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined;
1689 -
1690 - const tool: ToolInFlight = {
1691 - itemId,
1692 - itemType,
1693 - toolName,
1694 - title: titleForTool(itemType),
1695 - detail,
1696 - input: toolInput,
1697 - partialInputJson: "",
1698 - ...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}),
1699 - };
1700 - context.inFlightTools.set(index, tool);
1701 -
1702 - const stamp = yield* makeEventStamp();
1703 - yield* offerRuntimeEvent({
1704 - type: "item.started",
1705 - eventId: stamp.eventId,
1706 - provider: PROVIDER,
1707 - createdAt: stamp.createdAt,
1708 - threadId: context.session.threadId,
1709 - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
1710 - itemId: asRuntimeItemId(tool.itemId),
1711 - payload: {
1712 - itemType: tool.itemType,
1713 - status: "inProgress",
1714 - title: tool.title,
1715 - ...(tool.detail ? { detail: tool.detail } : {}),
1716 - data: {
1717 - toolName: tool.toolName,
1718 - input: toolInput,
1719 - },
1720 - },
1721 - providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
1722 - raw: {
1723 - source: "claude.sdk.message",
1724 - method: "claude/stream_event/content_block_start",
1725 - payload: message,
1726 - },
1727 - });
1728 - return;
1729 - }
1814 + const handleAssistantMessage = Effect.fn("handleAssistantMessage")(function* (
1815 + context: ClaudeSessionContext,
1816 + message: SDKMessage,
1817 + ) {
1818 + if (message.type !== "assistant") {
1819 + return;
1820 + }
1821
1731 - if (event.type === "content_block_stop") {
1732 - const { index } = event;
1733 - const assistantBlock = context.turnState?.assistantTextBlocks.get(index);
1734 - if (assistantBlock) {
1735 - assistantBlock.streamClosed = true;
1736 - yield* completeAssistantTextBlock(context, assistantBlock, {
1737 - rawMethod: "claude/stream_event/content_block_stop",
1738 - rawPayload: message,
1739 - });
1740 - return;
1741 - }
1742 - const tool = context.inFlightTools.get(index);
1743 - if (!tool) {
1744 - return;
1745 - }
1746 - }
1822 + // Auto-start a synthetic turn for assistant messages that arrive without
1823 + // an active turn (e.g., background agent/subagent responses between user prompts).
1824 + if (!context.turnState) {
1825 + const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4);
1826 + const startedAt = yield* nowIso;
1827 + context.turnState = {
1828 + turnId,
1829 + startedAt,
1830 + items: [],
1831 + assistantTextBlocks: new Map(),
1832 + assistantTextBlockOrder: [],
1833 + capturedProposedPlanKeys: new Set(),
1834 + nextSyntheticAssistantBlockIndex: -1,
1835 + };
1836 + context.session = {
1837 + ...context.session,
1838 + status: "running",
1839 + activeTurnId: turnId,
1840 + updatedAt: startedAt,
1841 + };
1842 + const turnStartedStamp = yield* makeEventStamp();
1843 + yield* offerRuntimeEvent({
1844 + type: "turn.started",
1845 + eventId: turnStartedStamp.eventId,
1846 + provider: PROVIDER,
1847 + createdAt: turnStartedStamp.createdAt,
1848 + threadId: context.session.threadId,
1849 + turnId,
1850 + payload: {},
1851 + providerRefs: {
1852 + ...nativeProviderRefs(context),
1853 + providerTurnId: turnId,
1854 + },
1855 + raw: {
1856 + source: "claude.sdk.message",
1857 + method: "claude/synthetic-turn-start",
1858 + payload: {},
1859 + },
1860 });
1861 + }
1862
1749 - const handleUserMessage = (
1750 - context: ClaudeSessionContext,
1751 - message: SDKMessage,
1752 - ): Effect.Effect<void> =>
1753 - Effect.gen(function* () {
1754 - if (message.type !== "user") {
1755 - return;
1756 - }
1757 -
1758 - if (context.turnState) {
1759 - context.turnState.items.push(message.message);
1760 - }
1761 -
1762 - for (const toolResult of toolResultBlocksFromUserMessage(message)) {
1763 - const toolEntry = Array.from(context.inFlightTools.entries()).find(
1764 - ([, tool]) => tool.itemId === toolResult.toolUseId,
1765 - );
1766 - if (!toolEntry) {
1767 - continue;
1768 - }
1769 -
1770 - const [index, tool] = toolEntry;
1771 - const itemStatus = toolResult.isError ? "failed" : "completed";
1772 - const toolData = {
1773 - toolName: tool.toolName,
1774 - input: tool.input,
1775 - result: toolResult.block,
1776 - };
1777 -
1778 - const updatedStamp = yield* makeEventStamp();
1779 - yield* offerRuntimeEvent({
1780 - type: "item.updated",
1781 - eventId: updatedStamp.eventId,
1782 - provider: PROVIDER,
1783 - createdAt: updatedStamp.createdAt,
1784 - threadId: context.session.threadId,
1785 - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
1786 - itemId: asRuntimeItemId(tool.itemId),
1787 - payload: {
1788 - itemType: tool.itemType,
1789 - status: toolResult.isError ? "failed" : "inProgress",
1790 - title: tool.title,
1791 - ...(tool.detail ? { detail: tool.detail } : {}),
1792 - data: toolData,
1793 - },
1794 - providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
1795 - raw: {
1796 - source: "claude.sdk.message",
1797 - method: "claude/user",
1798 - payload: message,
1799 - },
1800 - });
1801 -
1802 - const streamKind = toolResultStreamKind(tool.itemType);
1803 - if (streamKind && toolResult.text.length > 0 && context.turnState) {
1804 - const deltaStamp = yield* makeEventStamp();
1805 - yield* offerRuntimeEvent({
1806 - type: "content.delta",
1807 - eventId: deltaStamp.eventId,
1808 - provider: PROVIDER,
1809 - createdAt: deltaStamp.createdAt,
1810 - threadId: context.session.threadId,
1811 - turnId: context.turnState.turnId,
1812 - itemId: asRuntimeItemId(tool.itemId),
1813 - payload: {
1814 - streamKind,
1815 - delta: toolResult.text,
1816 - },
1817 - providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
1818 - raw: {
1819 - source: "claude.sdk.message",
1820 - method: "claude/user",
1821 - payload: message,
1822 - },
1823 - });
1824 - }
1825 -
1826 - const completedStamp = yield* makeEventStamp();
1827 - yield* offerRuntimeEvent({
1828 - type: "item.completed",
1829 - eventId: completedStamp.eventId,
1830 - provider: PROVIDER,
1831 - createdAt: completedStamp.createdAt,
1832 - threadId: context.session.threadId,
1833 - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
1834 - itemId: asRuntimeItemId(tool.itemId),
1835 - payload: {
1836 - itemType: tool.itemType,
1837 - status: itemStatus,
1838 - title: tool.title,
1839 - ...(tool.detail ? { detail: tool.detail } : {}),
1840 - data: toolData,
1841 - },
1842 - providerRefs: nativeProviderRefs(context, { providerItemId: tool.itemId }),
1843 - raw: {
1844 - source: "claude.sdk.message",
1845 - method: "claude/user",
1846 - payload: message,
1847 - },
1848 - });
1849 -
1850 - context.inFlightTools.delete(index);
1863 + const content = message.message?.content;
1864 + if (Array.isArray(content)) {
1865 + for (const block of content) {
1866 + if (!block || typeof block !== "object") {
1867 + continue;
1868 }
1852 - });
1853 -
1854 - const handleAssistantMessage = (
1855 - context: ClaudeSessionContext,
1856 - message: SDKMessage,
1857 - ): Effect.Effect<void> =>
1858 - Effect.gen(function* () {
1859 - if (message.type !== "assistant") {
1860 - return;
1869 + const toolUse = block as {
1870 + type?: unknown;
1871 + id?: unknown;
1872 + name?: unknown;
1873 + input?: unknown;
1874 + };
1875 + if (toolUse.type !== "tool_use" || toolUse.name !== "ExitPlanMode") {
1876 + continue;
1877 }
1862 -
1863 - // Auto-start a synthetic turn for assistant messages that arrive without
1864 - // an active turn (e.g., background agent/subagent responses between user prompts).
1865 - if (!context.turnState) {
1866 - const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4);
1867 - const startedAt = yield* nowIso;
1868 - context.turnState = {
1869 - turnId,
1870 - startedAt,
1871 - items: [],
1872 - assistantTextBlocks: new Map(),
1873 - assistantTextBlockOrder: [],
1874 - capturedProposedPlanKeys: new Set(),
1875 - nextSyntheticAssistantBlockIndex: -1,
1876 - };
1877 - context.session = {
1878 - ...context.session,
1879 - status: "running",
1880 - activeTurnId: turnId,
1881 - updatedAt: startedAt,
1882 - };
1883 - const turnStartedStamp = yield* makeEventStamp();
1884 - yield* offerRuntimeEvent({
1885 - type: "turn.started",
1886 - eventId: turnStartedStamp.eventId,
1887 - provider: PROVIDER,
1888 - createdAt: turnStartedStamp.createdAt,
1889 - threadId: context.session.threadId,
1890 - turnId,
1891 - payload: {},
1892 - providerRefs: {
1893 - ...nativeProviderRefs(context),
1894 - providerTurnId: turnId,
1895 - },
1896 - raw: {
1897 - source: "claude.sdk.message",
1898 - method: "claude/synthetic-turn-start",
1899 - payload: {},
1900 - },
1901 - });
1878 + const planMarkdown = extractExitPlanModePlan(toolUse.input);
1879 + if (!planMarkdown) {
1880 + continue;
1881 }
1882 + yield* emitProposedPlanCompleted(context, {
1883 + planMarkdown,
1884 + toolUseId: typeof toolUse.id === "string" ? toolUse.id : undefined,
1885 + rawSource: "claude.sdk.message",
1886 + rawMethod: "claude/assistant",
1887 + rawPayload: message,
1888 + });
1889 + }
1890 + }
1891
1904 - const content = message.message?.content;
1905 - if (Array.isArray(content)) {
1906 - for (const block of content) {
1907 - if (!block || typeof block !== "object") {
1908 - continue;
1909 - }
1910 - const toolUse = block as {
1911 - type?: unknown;
1912 - id?: unknown;
1913 - name?: unknown;
1914 - input?: unknown;
1915 - };
1916 - if (toolUse.type !== "tool_use" || toolUse.name !== "ExitPlanMode") {
1917 - continue;
1918 - }
1919 - const planMarkdown = extractExitPlanModePlan(toolUse.input);
1920 - if (!planMarkdown) {
1921 - continue;
1922 - }
1923 - yield* emitProposedPlanCompleted(context, {
1924 - planMarkdown,
1925 - toolUseId: typeof toolUse.id === "string" ? toolUse.id : undefined,
1926 - rawSource: "claude.sdk.message",
1927 - rawMethod: "claude/assistant",
1928 - rawPayload: message,
1929 - });
1930 - }
1931 - }
1892 + if (context.turnState) {
1893 + context.turnState.items.push(message.message);
1894 + yield* backfillAssistantTextBlocksFromSnapshot(context, message);
1895 + }
1896
1933 - if (context.turnState) {
1934 - context.turnState.items.push(message.message);
1935 - yield* backfillAssistantTextBlocksFromSnapshot(context, message);
1936 - }
1897 + context.lastAssistantUuid = message.uuid;
1898 + yield* updateResumeCursor(context);
1899 + });
1900
1938 - context.lastAssistantUuid = message.uuid;
1939 - yield* updateResumeCursor(context);
1940 - });
1901 + const handleResultMessage = Effect.fn("handleResultMessage")(function* (
1902 + context: ClaudeSessionContext,
1903 + message: SDKMessage,
1904 + ) {
1905 + if (message.type !== "result") {
1906 + return;
1907 + }
1908
1942 - const handleResultMessage = (
1943 - context: ClaudeSessionContext,
1944 - message: SDKMessage,
1945 - ): Effect.Effect<void> =>
1946 - Effect.gen(function* () {
1947 - if (message.type !== "result") {
1948 - return;
1949 - }
1909 + const status = turnStatusFromResult(message);
1910 + const errorMessage = message.subtype === "success" ? undefined : message.errors[0];
1911
1951 - const status = turnStatusFromResult(message);
1952 - const errorMessage = message.subtype === "success" ? undefined : message.errors[0];
1912 + if (status === "failed") {
1913 + yield* emitRuntimeError(context, errorMessage ?? "Claude turn failed.");
1914 + }
1915
1954 - if (status === "failed") {
1955 - yield* emitRuntimeError(context, errorMessage ?? "Claude turn failed.");
1956 - }
1916 + yield* completeTurn(context, status, errorMessage, message);
1917 + });
1918
1958 - yield* completeTurn(context, status, errorMessage, message);
1959 - });
1919 + const handleSystemMessage = Effect.fn("handleSystemMessage")(function* (
1920 + context: ClaudeSessionContext,
1921 + message: SDKMessage,
1922 + ) {
1923 + if (message.type !== "system") {
1924 + return;
1925 + }
1926
1961 - const handleSystemMessage = (
1962 - context: ClaudeSessionContext,
1963 - message: SDKMessage,
1964 - ): Effect.Effect<void> =>
1965 - Effect.gen(function* () {
1966 - if (message.type !== "system") {
1967 - return;
1968 - }
1927 + const stamp = yield* makeEventStamp();
1928 + const base = {
1929 + eventId: stamp.eventId,
1930 + provider: PROVIDER,
1931 + createdAt: stamp.createdAt,
1932 + threadId: context.session.threadId,
1933 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
1934 + providerRefs: nativeProviderRefs(context),
1935 + raw: {
1936 + source: "claude.sdk.message" as const,
1937 + method: sdkNativeMethod(message),
1938 + messageType: `${message.type}:${message.subtype}`,
1939 + payload: message,
1940 + },
1941 + };
1942
1970 - const stamp = yield* makeEventStamp();
1971 - const base = {
1972 - eventId: stamp.eventId,
1973 - provider: PROVIDER,
1974 - createdAt: stamp.createdAt,
1975 - threadId: context.session.threadId,
1976 - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
1977 - providerRefs: nativeProviderRefs(context),
1978 - raw: {
1979 - source: "claude.sdk.message" as const,
1980 - method: sdkNativeMethod(message),
1981 - messageType: `${message.type}:${message.subtype}`,
1982 - payload: message,
1943 + switch (message.subtype) {
1944 + case "init":
1945 + yield* offerRuntimeEvent({
1946 + ...base,
1947 + type: "session.configured",
1948 + payload: {
1949 + config: message as Record<string, unknown>,
1950 },
1984 - };
1985 -
1986 - switch (message.subtype) {
1987 - case "init":
1988 - yield* offerRuntimeEvent({
1989 - ...base,
1990 - type: "session.configured",
1991 - payload: {
1992 - config: message as Record<string, unknown>,
1993 - },
1994 - });
1995 - return;
1996 - case "status":
1997 - yield* offerRuntimeEvent({
1998 - ...base,
1999 - type: "session.state.changed",
2000 - payload: {
2001 - state: message.status === "compacting" ? "waiting" : "running",
2002 - reason: `status:${message.status ?? "active"}`,
2003 - detail: message,
2004 - },
2005 - });
2006 - return;
2007 - case "compact_boundary":
2008 - yield* offerRuntimeEvent({
2009 - ...base,
2010 - type: "thread.state.changed",
2011 - payload: {
2012 - state: "compacted",
2013 - detail: message,
2014 - },
2015 - });
2016 - return;
2017 - case "hook_started":
2018 - yield* offerRuntimeEvent({
2019 - ...base,
2020 - type: "hook.started",
2021 - payload: {
2022 - hookId: message.hook_id,
2023 - hookName: message.hook_name,
2024 - hookEvent: message.hook_event,
2025 - },
2026 - });
2027 - return;
2028 - case "hook_progress":
2029 - yield* offerRuntimeEvent({
2030 - ...base,
2031 - type: "hook.progress",
2032 - payload: {
2033 - hookId: message.hook_id,
2034 - output: message.output,
2035 - stdout: message.stdout,
2036 - stderr: message.stderr,
2037 - },
2038 - });
2039 - return;
2040 - case "hook_response":
2041 - yield* offerRuntimeEvent({
2042 - ...base,
2043 - type: "hook.completed",
2044 - payload: {
2045 - hookId: message.hook_id,
2046 - outcome: message.outcome,
2047 - output: message.output,
2048 - stdout: message.stdout,
2049 - stderr: message.stderr,
2050 - ...(typeof message.exit_code === "number" ? { exitCode: message.exit_code } : {}),
2051 - },
2052 - });
2053 - return;
2054 - case "task_started":
2055 - yield* offerRuntimeEvent({
2056 - ...base,
2057 - type: "task.started",
2058 - payload: {
2059 - taskId: RuntimeTaskId.makeUnsafe(message.task_id),
2060 - description: message.description,
2061 - ...(message.task_type ? { taskType: message.task_type } : {}),
2062 - },
2063 - });
2064 - return;
2065 - case "task_progress":
2066 - if (message.usage) {
2067 - const normalizedUsage = normalizeClaudeTokenUsage(
2068 - message.usage,
2069 - context.lastKnownContextWindow,
2070 - );
2071 - if (normalizedUsage) {
2072 - context.lastKnownTokenUsage = normalizedUsage;
2073 - const usageStamp = yield* makeEventStamp();
2074 - yield* offerRuntimeEvent({
2075 - ...base,
2076 - eventId: usageStamp.eventId,
2077 - createdAt: usageStamp.createdAt,
2078 - type: "thread.token-usage.updated",
2079 - payload: {
2080 - usage: normalizedUsage,
2081 - },
2082 - });
2083 - }
2084 - }
2085 - yield* offerRuntimeEvent({
2086 - ...base,
2087 - type: "task.progress",
2088 - payload: {
2089 - taskId: RuntimeTaskId.makeUnsafe(message.task_id),
2090 - description: message.description,
2091 - ...(message.summary ? { summary: message.summary } : {}),
2092 - ...(message.usage ? { usage: message.usage } : {}),
2093 - ...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),
2094 - },
2095 - });
2096 - return;
2097 - case "task_notification":
2098 - if (message.usage) {
2099 - const normalizedUsage = normalizeClaudeTokenUsage(
2100 - message.usage,
2101 - context.lastKnownContextWindow,
2102 - );
2103 - if (normalizedUsage) {
2104 - context.lastKnownTokenUsage = normalizedUsage;
2105 - const usageStamp = yield* makeEventStamp();
2106 - yield* offerRuntimeEvent({
2107 - ...base,
2108 - eventId: usageStamp.eventId,
2109 - createdAt: usageStamp.createdAt,
2110 - type: "thread.token-usage.updated",
2111 - payload: {
2112 - usage: normalizedUsage,
2113 - },
2114 - });
2115 - }
2116 - }
1951 + });
1952 + return;
1953 + case "status":
1954 + yield* offerRuntimeEvent({
1955 + ...base,
1956 + type: "session.state.changed",
1957 + payload: {
1958 + state: message.status === "compacting" ? "waiting" : "running",
1959 + reason: `status:${message.status ?? "active"}`,
1960 + detail: message,
1961 + },
1962 + });
1963 + return;
1964 + case "compact_boundary":
1965 + yield* offerRuntimeEvent({
1966 + ...base,
1967 + type: "thread.state.changed",
1968 + payload: {
1969 + state: "compacted",
1970 + detail: message,
1971 + },
1972 + });
1973 + return;
1974 + case "hook_started":
1975 + yield* offerRuntimeEvent({
1976 + ...base,
1977 + type: "hook.started",
1978 + payload: {
1979 + hookId: message.hook_id,
1980 + hookName: message.hook_name,
1981 + hookEvent: message.hook_event,
1982 + },
1983 + });
1984 + return;
1985 + case "hook_progress":
1986 + yield* offerRuntimeEvent({
1987 + ...base,
1988 + type: "hook.progress",
1989 + payload: {
1990 + hookId: message.hook_id,
1991 + output: message.output,
1992 + stdout: message.stdout,
1993 + stderr: message.stderr,
1994 + },
1995 + });
1996 + return;
1997 + case "hook_response":
1998 + yield* offerRuntimeEvent({
1999 + ...base,
2000 + type: "hook.completed",
2001 + payload: {
2002 + hookId: message.hook_id,
2003 + outcome: message.outcome,
2004 + output: message.output,
2005 + stdout: message.stdout,
2006 + stderr: message.stderr,
2007 + ...(typeof message.exit_code === "number" ? { exitCode: message.exit_code } : {}),
2008 + },
2009 + });
2010 + return;
2011 + case "task_started":
2012 + yield* offerRuntimeEvent({
2013 + ...base,
2014 + type: "task.started",
2015 + payload: {
2016 + taskId: RuntimeTaskId.makeUnsafe(message.task_id),
2017 + description: message.description,
2018 + ...(message.task_type ? { taskType: message.task_type } : {}),
2019 + },
2020 + });
2021 + return;
2022 + case "task_progress":
2023 + if (message.usage) {
2024 + const normalizedUsage = normalizeClaudeTokenUsage(
2025 + message.usage,
2026 + context.lastKnownContextWindow,
2027 + );
2028 + if (normalizedUsage) {
2029 + context.lastKnownTokenUsage = normalizedUsage;
2030 + const usageStamp = yield* makeEventStamp();
2031 yield* offerRuntimeEvent({
2032 ...base,
2119 - type: "task.completed",
2033 + eventId: usageStamp.eventId,
2034 + createdAt: usageStamp.createdAt,
2035 + type: "thread.token-usage.updated",
2036 payload: {
2121 - taskId: RuntimeTaskId.makeUnsafe(message.task_id),
2122 - status: message.status,
2123 - ...(message.summary ? { summary: message.summary } : {}),
2124 - ...(message.usage ? { usage: message.usage } : {}),
2037 + usage: normalizedUsage,
2038 },
2039 });
2127 - return;
2128 - case "files_persisted":
2040 + }
2041 + }
2042 + yield* offerRuntimeEvent({
2043 + ...base,
2044 + type: "task.progress",
2045 + payload: {
2046 + taskId: RuntimeTaskId.makeUnsafe(message.task_id),
2047 + description: message.description,
2048 + ...(message.summary ? { summary: message.summary } : {}),
2049 + ...(message.usage ? { usage: message.usage } : {}),
2050 + ...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),
2051 + },
2052 + });
2053 + return;
2054 + case "task_notification":
2055 + if (message.usage) {
2056 + const normalizedUsage = normalizeClaudeTokenUsage(
2057 + message.usage,
2058 + context.lastKnownContextWindow,
2059 + );
2060 + if (normalizedUsage) {
2061 + context.lastKnownTokenUsage = normalizedUsage;
2062 + const usageStamp = yield* makeEventStamp();
2063 yield* offerRuntimeEvent({
2064 ...base,
2131 - type: "files.persisted",
2065 + eventId: usageStamp.eventId,
2066 + createdAt: usageStamp.createdAt,
2067 + type: "thread.token-usage.updated",
2068 payload: {
2133 - files: Array.isArray(message.files)
2134 - ? message.files.map((file: { filename: string; file_id: string }) => ({
2135 - filename: file.filename,
2136 - fileId: file.file_id,
2137 - }))
2138 - : [],
2139 - ...(Array.isArray(message.failed)
2140 - ? {
2141 - failed: message.failed.map((entry: { filename: string; error: string }) => ({
2142 - filename: entry.filename,
2143 - error: entry.error,
2144 - })),
2145 - }
2146 - : {}),
2069 + usage: normalizedUsage,
2070 },
2071 });
2149 - return;
2150 - default:
2151 - yield* emitRuntimeWarning(
2152 - context,
2153 - `Unhandled Claude system message subtype '${message.subtype}'.`,
2154 - message,
2155 - );
2156 - return;
2072 + }
2073 }
2158 - });
2159 -
2160 - const handleSdkTelemetryMessage = (
2161 - context: ClaudeSessionContext,
2162 - message: SDKMessage,
2163 - ): Effect.Effect<void> =>
2164 - Effect.gen(function* () {
2165 - const stamp = yield* makeEventStamp();
2166 - const base = {
2167 - eventId: stamp.eventId,
2168 - provider: PROVIDER,
2169 - createdAt: stamp.createdAt,
2170 - threadId: context.session.threadId,
2171 - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
2172 - providerRefs: nativeProviderRefs(context),
2173 - raw: {
2174 - source: "claude.sdk.message" as const,
2175 - method: sdkNativeMethod(message),
2176 - messageType: message.type,
2177 - payload: message,
2074 + yield* offerRuntimeEvent({
2075 + ...base,
2076 + type: "task.completed",
2077 + payload: {
2078 + taskId: RuntimeTaskId.makeUnsafe(message.task_id),
2079 + status: message.status,
2080 + ...(message.summary ? { summary: message.summary } : {}),
2081 + ...(message.usage ? { usage: message.usage } : {}),
2082 },
2179 - };
2180 -
2181 - if (message.type === "tool_progress") {
2182 - yield* offerRuntimeEvent({
2183 - ...base,
2184 - type: "tool.progress",
2185 - payload: {
2186 - toolUseId: message.tool_use_id,
2187 - toolName: message.tool_name,
2188 - elapsedSeconds: message.elapsed_time_seconds,
2189 - ...(message.task_id ? { summary: `task:${message.task_id}` } : {}),
2190 - },
2191 - });
2192 - return;
2193 - }
2194 -
2195 - if (message.type === "tool_use_summary") {
2196 - yield* offerRuntimeEvent({
2197 - ...base,
2198 - type: "tool.summary",
2199 - payload: {
2200 - summary: message.summary,
2201 - ...(message.preceding_tool_use_ids.length > 0
2202 - ? { precedingToolUseIds: message.preceding_tool_use_ids }
2203 - : {}),
2204 - },
2205 - });
2206 - return;
2207 - }
2083 + });
2084 + return;
2085 + case "files_persisted":
2086 + yield* offerRuntimeEvent({
2087 + ...base,
2088 + type: "files.persisted",
2089 + payload: {
2090 + files: Array.isArray(message.files)
2091 + ? message.files.map((file: { filename: string; file_id: string }) => ({
2092 + filename: file.filename,
2093 + fileId: file.file_id,
2094 + }))
2095 + : [],
2096 + ...(Array.isArray(message.failed)
2097 + ? {
2098 + failed: message.failed.map((entry: { filename: string; error: string }) => ({
2099 + filename: entry.filename,
2100 + error: entry.error,
2101 + })),
2102 + }
2103 + : {}),
2104 + },
2105 + });
2106 + return;
2107 + default:
2108 + yield* emitRuntimeWarning(
2109 + context,
2110 + `Unhandled Claude system message subtype '${message.subtype}'.`,
2111 + message,
2112 + );
2113 + return;
2114 + }
2115 + });
2116
2209 - if (message.type === "auth_status") {
2210 - yield* offerRuntimeEvent({
2211 - ...base,
2212 - type: "auth.status",
2213 - payload: {
2214 - isAuthenticating: message.isAuthenticating,
2215 - output: message.output,
2216 - ...(message.error ? { error: message.error } : {}),
2217 - },
2218 - });
2219 - return;
2220 - }
2117 + const handleSdkTelemetryMessage = Effect.fn("handleSdkTelemetryMessage")(function* (
2118 + context: ClaudeSessionContext,
2119 + message: SDKMessage,
2120 + ) {
2121 + const stamp = yield* makeEventStamp();
2122 + const base = {
2123 + eventId: stamp.eventId,
2124 + provider: PROVIDER,
2125 + createdAt: stamp.createdAt,
2126 + threadId: context.session.threadId,
2127 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
2128 + providerRefs: nativeProviderRefs(context),
2129 + raw: {
2130 + source: "claude.sdk.message" as const,
2131 + method: sdkNativeMethod(message),
2132 + messageType: message.type,
2133 + payload: message,
2134 + },
2135 + };
2136
2222 - if (message.type === "rate_limit_event") {
2223 - yield* offerRuntimeEvent({
2224 - ...base,
2225 - type: "account.rate-limits.updated",
2226 - payload: {
2227 - rateLimits: message,
2228 - },
2229 - });
2230 - return;
2231 - }
2137 + if (message.type === "tool_progress") {
2138 + yield* offerRuntimeEvent({
2139 + ...base,
2140 + type: "tool.progress",
2141 + payload: {
2142 + toolUseId: message.tool_use_id,
2143 + toolName: message.tool_name,
2144 + elapsedSeconds: message.elapsed_time_seconds,
2145 + ...(message.task_id ? { summary: `task:${message.task_id}` } : {}),
2146 + },
2147 });
2148 + return;
2149 + }
2150
2234 - const handleSdkMessage = (
2235 - context: ClaudeSessionContext,
2236 - message: SDKMessage,
2237 - ): Effect.Effect<void> =>
2238 - Effect.gen(function* () {
2239 - yield* logNativeSdkMessage(context, message);
2240 - yield* ensureThreadId(context, message);
2241 -
2242 - switch (message.type) {
2243 - case "stream_event":
2244 - yield* handleStreamEvent(context, message);
2245 - return;
2246 - case "user":
2247 - yield* handleUserMessage(context, message);
2248 - return;
2249 - case "assistant":
2250 - yield* handleAssistantMessage(context, message);
2251 - return;
2252 - case "result":
2253 - yield* handleResultMessage(context, message);
2254 - return;
2255 - case "system":
2256 - yield* handleSystemMessage(context, message);
2257 - return;
2258 - case "tool_progress":
2259 - case "tool_use_summary":
2260 - case "auth_status":
2261 - case "rate_limit_event":
2262 - yield* handleSdkTelemetryMessage(context, message);
2263 - return;
2264 - default:
2265 - yield* emitRuntimeWarning(
2266 - context,
2267 - `Unhandled Claude SDK message type '${message.type}'.`,
2268 - message,
2269 - );
2270 - return;
2271 - }
2151 + if (message.type === "tool_use_summary") {
2152 + yield* offerRuntimeEvent({
2153 + ...base,
2154 + type: "tool.summary",
2155 + payload: {
2156 + summary: message.summary,
2157 + ...(message.preceding_tool_use_ids.length > 0
2158 + ? { precedingToolUseIds: message.preceding_tool_use_ids }
2159 + : {}),
2160 + },
2161 });
2162 + return;
2163 + }
2164
2274 - const runSdkStream = (context: ClaudeSessionContext): Effect.Effect<void, Error> =>
2275 - Stream.fromAsyncIterable(context.query, (cause) =>
2276 - toError(cause, "Claude runtime stream failed."),
2277 - ).pipe(
2278 - Stream.takeWhile(() => !context.stopped),
2279 - Stream.runForEach((message) => handleSdkMessage(context, message)),
2280 - );
2281 -
2282 - const handleStreamExit = (
2283 - context: ClaudeSessionContext,
2284 - exit: Exit.Exit<void, Error>,
2285 - ): Effect.Effect<void> =>
2286 - Effect.gen(function* () {
2287 - if (context.stopped) {
2288 - return;
2289 - }
2290 -
2291 - if (Exit.isFailure(exit)) {
2292 - if (isClaudeInterruptedCause(exit.cause)) {
2293 - if (context.turnState) {
2294 - yield* completeTurn(
2295 - context,
2296 - "interrupted",
2297 - interruptionMessageFromClaudeCause(exit.cause),
2298 - );
2299 - }
2300 - } else {
2301 - const message = messageFromClaudeStreamCause(
2302 - exit.cause,
2303 - "Claude runtime stream failed.",
2304 - );
2305 - yield* emitRuntimeError(context, message, Cause.pretty(exit.cause));
2306 - yield* completeTurn(context, "failed", message);
2307 - }
2308 - } else if (context.turnState) {
2309 - yield* completeTurn(context, "interrupted", "Claude runtime stream ended.");
2310 - }
2311 -
2312 - yield* stopSessionInternal(context, {
2313 - emitExitEvent: true,
2314 - });
2165 + if (message.type === "auth_status") {
2166 + yield* offerRuntimeEvent({
2167 + ...base,
2168 + type: "auth.status",
2169 + payload: {
2170 + isAuthenticating: message.isAuthenticating,
2171 + output: message.output,
2172 + ...(message.error ? { error: message.error } : {}),
2173 + },
2174 });
2175 + return;
2176 + }
2177
2317 - const stopSessionInternal = (
2318 - context: ClaudeSessionContext,
2319 - options?: { readonly emitExitEvent?: boolean },
2320 - ): Effect.Effect<void> =>
2321 - Effect.gen(function* () {
2322 - if (context.stopped) return;
2323 -
2324 - context.stopped = true;
2325 -
2326 - for (const [requestId, pending] of context.pendingApprovals) {
2327 - yield* Deferred.succeed(pending.decision, "cancel");
2328 - const stamp = yield* makeEventStamp();
2329 - yield* offerRuntimeEvent({
2330 - type: "request.resolved",
2331 - eventId: stamp.eventId,
2332 - provider: PROVIDER,
2333 - createdAt: stamp.createdAt,
2334 - threadId: context.session.threadId,
2335 - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
2336 - requestId: asRuntimeRequestId(requestId),
2337 - payload: {
2338 - requestType: pending.requestType,
2339 - decision: "cancel",
2340 - },
2341 - providerRefs: nativeProviderRefs(context),
2342 - });
2343 - }
2344 - context.pendingApprovals.clear();
2345 -
2346 - if (context.turnState) {
2347 - yield* completeTurn(context, "interrupted", "Session stopped.");
2348 - }
2349 -
2350 - yield* Queue.shutdown(context.promptQueue);
2351 -
2352 - const streamFiber = context.streamFiber;
2353 - context.streamFiber = undefined;
2354 - if (streamFiber && streamFiber.pollUnsafe() === undefined) {
2355 - yield* Fiber.interrupt(streamFiber);
2356 - }
2357 -
2358 - // @effect-diagnostics-next-line tryCatchInEffectGen:off
2359 - try {
2360 - context.query.close();
2361 - } catch (cause) {
2362 - yield* emitRuntimeError(context, "Failed to close Claude runtime query.", cause);
2363 - }
2364 -
2365 - const updatedAt = yield* nowIso;
2366 - context.session = {
2367 - ...context.session,
2368 - status: "closed",
2369 - activeTurnId: undefined,
2370 - updatedAt,
2371 - };
2372 -
2373 - if (options?.emitExitEvent !== false) {
2374 - const stamp = yield* makeEventStamp();
2375 - yield* offerRuntimeEvent({
2376 - type: "session.exited",
2377 - eventId: stamp.eventId,
2378 - provider: PROVIDER,
2379 - createdAt: stamp.createdAt,
2380 - threadId: context.session.threadId,
2381 - payload: {
2382 - reason: "Session stopped",
2383 - exitKind: "graceful",
2384 - },
2385 - providerRefs: {},
2386 - });
2387 - }
2388 -
2389 - sessions.delete(context.session.threadId);
2178 + if (message.type === "rate_limit_event") {
2179 + yield* offerRuntimeEvent({
2180 + ...base,
2181 + type: "account.rate-limits.updated",
2182 + payload: {
2183 + rateLimits: message,
2184 + },
2185 });
2391 -
2392 - const requireSession = (
2393 - threadId: ThreadId,
2394 - ): Effect.Effect<ClaudeSessionContext, ProviderAdapterError> => {
2395 - const context = sessions.get(threadId);
2396 - if (!context) {
2397 - return Effect.fail(
2398 - new ProviderAdapterSessionNotFoundError({
2399 - provider: PROVIDER,
2400 - threadId,
2401 - }),
2402 - );
2403 - }
2404 - if (context.stopped || context.session.status === "closed") {
2405 - return Effect.fail(
2406 - new ProviderAdapterSessionClosedError({
2407 - provider: PROVIDER,
2408 - threadId,
2409 - }),
2186 + return;
2187 + }
2188 + });
2189 +
2190 + const handleSdkMessage = Effect.fn("handleSdkMessage")(function* (
2191 + context: ClaudeSessionContext,
2192 + message: SDKMessage,
2193 + ) {
2194 + yield* logNativeSdkMessage(context, message);
2195 + yield* ensureThreadId(context, message);
2196 +
2197 + switch (message.type) {
2198 + case "stream_event":
2199 + yield* handleStreamEvent(context, message);
2200 + return;
2201 + case "user":
2202 + yield* handleUserMessage(context, message);
2203 + return;
2204 + case "assistant":
2205 + yield* handleAssistantMessage(context, message);
2206 + return;
2207 + case "result":
2208 + yield* handleResultMessage(context, message);
2209 + return;
2210 + case "system":
2211 + yield* handleSystemMessage(context, message);
2212 + return;
2213 + case "tool_progress":
2214 + case "tool_use_summary":
2215 + case "auth_status":
2216 + case "rate_limit_event":
2217 + yield* handleSdkTelemetryMessage(context, message);
2218 + return;
2219 + default:
2220 + yield* emitRuntimeWarning(
2221 + context,
2222 + `Unhandled Claude SDK message type '${message.type}'.`,
2223 + message,
2224 );
2411 - }
2412 - return Effect.succeed(context);
2413 - };
2225 + return;
2226 + }
2227 + });
2228
2415 - const startSession: ClaudeAdapterShape["startSession"] = (input) =>
2416 - Effect.gen(function* () {
2417 - if (input.provider !== undefined && input.provider !== PROVIDER) {
2418 - return yield* new ProviderAdapterValidationError({
2419 - provider: PROVIDER,
2420 - operation: "startSession",
2421 - issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
2422 - });
2229 + const runSdkStream = (context: ClaudeSessionContext): Effect.Effect<void, Error> =>
2230 + Stream.fromAsyncIterable(context.query, (cause) =>
2231 + toError(cause, "Claude runtime stream failed."),
2232 + ).pipe(
2233 + Stream.takeWhile(() => !context.stopped),
2234 + Stream.runForEach((message) => handleSdkMessage(context, message)),
2235 + );
2236 +
2237 + const handleStreamExit = Effect.fn("handleStreamExit")(function* (
2238 + context: ClaudeSessionContext,
2239 + exit: Exit.Exit<void, Error>,
2240 + ) {
2241 + if (context.stopped) {
2242 + return;
2243 + }
2244 +
2245 + if (Exit.isFailure(exit)) {
2246 + if (isClaudeInterruptedCause(exit.cause)) {
2247 + if (context.turnState) {
2248 + yield* completeTurn(
2249 + context,
2250 + "interrupted",
2251 + interruptionMessageFromClaudeCause(exit.cause),
2252 + );
2253 }
2254 + } else {
2255 + const message = messageFromClaudeStreamCause(exit.cause, "Claude runtime stream failed.");
2256 + yield* emitRuntimeError(context, message, Cause.pretty(exit.cause));
2257 + yield* completeTurn(context, "failed", message);
2258 + }
2259 + } else if (context.turnState) {
2260 + yield* completeTurn(context, "interrupted", "Claude runtime stream ended.");
2261 + }
2262
2425 - const startedAt = yield* nowIso;
2426 - const resumeState = readClaudeResumeState(input.resumeCursor);
2427 - const threadId = input.threadId;
2428 - const existingResumeSessionId = resumeState?.resume;
2429 - const newSessionId =
2430 - existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined;
2431 - const sessionId = existingResumeSessionId ?? newSessionId;
2432 -
2433 - const promptQueue = yield* Queue.unbounded<PromptQueueItem>();
2434 - const prompt = Stream.fromQueue(promptQueue).pipe(
2435 - Stream.filter((item) => item.type === "message"),
2436 - Stream.map((item) => item.message),
2437 - Stream.catchCause((cause) =>
2438 - Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
2439 - ),
2440 - Stream.toAsyncIterable,
2441 - );
2263 + yield* stopSessionInternal(context, {
2264 + emitExitEvent: true,
2265 + });
2266 + });
2267
2443 - const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
2444 - const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
2445 - const inFlightTools = new Map<number, ToolInFlight>();
2446 -
2447 - const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);
2448 -
2449 - /**
2450 - * Handle AskUserQuestion tool calls by emitting a `user-input.requested`
2451 - * runtime event and waiting for the user to respond via `respondToUserInput`.
2452 - */
2453 - const handleAskUserQuestion = (
2454 - context: ClaudeSessionContext,
2455 - toolInput: Record<string, unknown>,
2456 - callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string },
2457 - ) =>
2458 - Effect.gen(function* () {
2459 - const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4);
2460 -
2461 - // Parse questions from the SDK's AskUserQuestion input.
2462 - const rawQuestions = Array.isArray(toolInput.questions) ? toolInput.questions : [];
2463 - const questions: Array<UserInputQuestion> = rawQuestions.map(
2464 - (q: Record<string, unknown>, idx: number) => ({
2465 - id: typeof q.header === "string" ? q.header : `q-${idx}`,
2466 - header: typeof q.header === "string" ? q.header : `Question ${idx + 1}`,
2467 - question: typeof q.question === "string" ? q.question : "",
2468 - options: Array.isArray(q.options)
2469 - ? q.options.map((opt: Record<string, unknown>) => ({
2470 - label: typeof opt.label === "string" ? opt.label : "",
2471 - description: typeof opt.description === "string" ? opt.description : "",
2472 - }))
2473 - : [],
2474 - multiSelect: typeof q.multiSelect === "boolean" ? q.multiSelect : false,
2475 - }),
2476 - );
2477 -
2478 - const answersDeferred = yield* Deferred.make<ProviderUserInputAnswers>();
2479 - let aborted = false;
2480 - const pendingInput: PendingUserInput = {
2481 - questions,
2482 - answers: answersDeferred,
2483 - };
2484 -
2485 - // Emit user-input.requested so the UI can present the questions.
2486 - const requestedStamp = yield* makeEventStamp();
2487 - yield* offerRuntimeEvent({
2488 - type: "user-input.requested",
2489 - eventId: requestedStamp.eventId,
2490 - provider: PROVIDER,
2491 - createdAt: requestedStamp.createdAt,
2492 - threadId: context.session.threadId,
2493 - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
2494 - requestId: asRuntimeRequestId(requestId),
2495 - payload: { questions },
2496 - providerRefs: nativeProviderRefs(context, {
2497 - providerItemId: callbackOptions.toolUseID,
2498 - }),
2499 - raw: {
2500 - source: "claude.sdk.permission",
2501 - method: "canUseTool/AskUserQuestion",
2502 - payload: { toolName: "AskUserQuestion", input: toolInput },
2503 - },
2504 - });
2268 + const stopSessionInternal = Effect.fn("stopSessionInternal")(function* (
2269 + context: ClaudeSessionContext,
2270 + options?: { readonly emitExitEvent?: boolean },
2271 + ) {
2272 + if (context.stopped) return;
2273 +
2274 + context.stopped = true;
2275 +
2276 + for (const [requestId, pending] of context.pendingApprovals) {
2277 + yield* Deferred.succeed(pending.decision, "cancel");
2278 + const stamp = yield* makeEventStamp();
2279 + yield* offerRuntimeEvent({
2280 + type: "request.resolved",
2281 + eventId: stamp.eventId,
2282 + provider: PROVIDER,
2283 + createdAt: stamp.createdAt,
2284 + threadId: context.session.threadId,
2285 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
2286 + requestId: asRuntimeRequestId(requestId),
2287 + payload: {
2288 + requestType: pending.requestType,
2289 + decision: "cancel",
2290 + },
2291 + providerRefs: nativeProviderRefs(context),
2292 + });
2293 + }
2294 + context.pendingApprovals.clear();
2295
2506 - pendingUserInputs.set(requestId, pendingInput);
2507 -
2508 - // Handle abort (e.g. turn interrupted while waiting for user input).
2509 - const onAbort = () => {
2510 - if (!pendingUserInputs.has(requestId)) {
2511 - return;
2512 - }
2513 - aborted = true;
2514 - pendingUserInputs.delete(requestId);
2515 - Effect.runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers));
2516 - };
2517 - callbackOptions.signal.addEventListener("abort", onAbort, { once: true });
2518 -
2519 - // Block until the user provides answers.
2520 - const answers = yield* Deferred.await(answersDeferred);
2521 - pendingUserInputs.delete(requestId);
2522 -
2523 - // Emit user-input.resolved so the UI knows the interaction completed.
2524 - const resolvedStamp = yield* makeEventStamp();
2525 - yield* offerRuntimeEvent({
2526 - type: "user-input.resolved",
2527 - eventId: resolvedStamp.eventId,
2528 - provider: PROVIDER,
2529 - createdAt: resolvedStamp.createdAt,
2530 - threadId: context.session.threadId,
2531 - ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
2532 - requestId: asRuntimeRequestId(requestId),
2533 - payload: { answers },
2534 - providerRefs: nativeProviderRefs(context, {
2535 - providerItemId: callbackOptions.toolUseID,
2536 - }),
2537 - raw: {
2538 - source: "claude.sdk.permission",
2539 - method: "canUseTool/AskUserQuestion/resolved",
2540 - payload: { answers },
2541 - },
2542 - });
2296 + if (context.turnState) {
2297 + yield* completeTurn(context, "interrupted", "Session stopped.");
2298 + }
2299
2544 - if (aborted) {
2545 - return {
2546 - behavior: "deny",
2547 - message: "User cancelled tool execution.",
2548 - } satisfies PermissionResult;
2549 - }
2300 + yield* Queue.shutdown(context.promptQueue);
2301
2551 - // Return the answers to the SDK in the expected format:
2552 - // { questions: [...], answers: { questionText: selectedLabel } }
2553 - return {
2554 - behavior: "allow",
2555 - updatedInput: {
2556 - questions: toolInput.questions,
2557 - answers,
2558 - },
2559 - } satisfies PermissionResult;
2560 - });
2561 -
2562 - const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) =>
2563 - Effect.runPromise(
2564 - Effect.gen(function* () {
2565 - const context = yield* Ref.get(contextRef);
2566 - if (!context) {
2567 - return {
2568 - behavior: "deny",
2569 - message: "Claude session context is unavailable.",
2570 - } satisfies PermissionResult;
2571 - }
2572 -
2573 - // Handle AskUserQuestion: surface clarifying questions to the
2574 - // user via the user-input runtime event channel, regardless of
2575 - // runtime mode (plan mode relies on this heavily).
2576 - if (toolName === "AskUserQuestion") {
2577 - return yield* handleAskUserQuestion(context, toolInput, callbackOptions);
2578 - }
2579 -
2580 - if (toolName === "ExitPlanMode") {
2581 - const planMarkdown = extractExitPlanModePlan(toolInput);
2582 - if (planMarkdown) {
2583 - yield* emitProposedPlanCompleted(context, {
2584 - planMarkdown,
2585 - toolUseId: callbackOptions.toolUseID,
2586 - rawSource: "claude.sdk.permission",
2587 - rawMethod: "canUseTool/ExitPlanMode",
2588 - rawPayload: {
2589 - toolName,
2590 - input: toolInput,
2591 - },
2592 - });
2593 - }
2302 + const streamFiber = context.streamFiber;
2303 + context.streamFiber = undefined;
2304 + if (streamFiber && streamFiber.pollUnsafe() === undefined) {
2305 + yield* Fiber.interrupt(streamFiber);
2306 + }
2307
2595 - return {
2596 - behavior: "deny",
2597 - message:
2598 - "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
2599 - } satisfies PermissionResult;
2600 - }
2601 -
2602 - const runtimeMode = input.runtimeMode ?? "full-access";
2603 - if (runtimeMode === "full-access") {
2604 - return {
2605 - behavior: "allow",
2606 - updatedInput: toolInput,
2607 - } satisfies PermissionResult;
2608 - }
2609 -
2610 - const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4);
2611 - const requestType = classifyRequestType(toolName);
2612 - const detail = summarizeToolRequest(toolName, toolInput);
2613 - const decisionDeferred = yield* Deferred.make<ProviderApprovalDecision>();
2614 - const pendingApproval: PendingApproval = {
2615 - requestType,
2616 - detail,
2617 - decision: decisionDeferred,
2618 - ...(callbackOptions.suggestions
2619 - ? { suggestions: callbackOptions.suggestions }
2620 - : {}),
2621 - };
2622 -
2623 - const requestedStamp = yield* makeEventStamp();
2624 - yield* offerRuntimeEvent({
2625 - type: "request.opened",
2626 - eventId: requestedStamp.eventId,
2627 - provider: PROVIDER,
2628 - createdAt: requestedStamp.createdAt,
2629 - threadId: context.session.threadId,
2630 - ...(context.turnState
2631 - ? { turnId: asCanonicalTurnId(context.turnState.turnId) }
2632 - : {}),
2633 - requestId: asRuntimeRequestId(requestId),
2634 - payload: {
2635 - requestType,
2636 - detail,
2637 - args: {
2638 - toolName,
2639 - input: toolInput,
2640 - ...(callbackOptions.toolUseID ? { toolUseId: callbackOptions.toolUseID } : {}),
2641 - },
2642 - },
2643 - providerRefs: nativeProviderRefs(context, {
2644 - providerItemId: callbackOptions.toolUseID,
2645 - }),
2646 - raw: {
2647 - source: "claude.sdk.permission",
2648 - method: "canUseTool/request",
2649 - payload: {
2650 - toolName,
2651 - input: toolInput,
2652 - },
2653 - },
2654 - });
2655 -
2656 - pendingApprovals.set(requestId, pendingApproval);
2657 -
2658 - const onAbort = () => {
2659 - if (!pendingApprovals.has(requestId)) {
2660 - return;
2661 - }
2662 - pendingApprovals.delete(requestId);
2663 - Effect.runFork(Deferred.succeed(decisionDeferred, "cancel"));
2664 - };
2665 -
2666 - callbackOptions.signal.addEventListener("abort", onAbort, {
2667 - once: true,
2668 - });
2669 -
2670 - const decision = yield* Deferred.await(decisionDeferred);
2671 - pendingApprovals.delete(requestId);
2672 -
2673 - const resolvedStamp = yield* makeEventStamp();
2674 - yield* offerRuntimeEvent({
2675 - type: "request.resolved",
2676 - eventId: resolvedStamp.eventId,
2677 - provider: PROVIDER,
2678 - createdAt: resolvedStamp.createdAt,
2679 - threadId: context.session.threadId,
2680 - ...(context.turnState
2681 - ? { turnId: asCanonicalTurnId(context.turnState.turnId) }
2682 - : {}),
2683 - requestId: asRuntimeRequestId(requestId),
2684 - payload: {
2685 - requestType,
2686 - decision,
2687 - },
2688 - providerRefs: nativeProviderRefs(context, {
2689 - providerItemId: callbackOptions.toolUseID,
2690 - }),
2691 - raw: {
2692 - source: "claude.sdk.permission",
2693 - method: "canUseTool/decision",
2694 - payload: {
2695 - decision,
2696 - },
2697 - },
2698 - });
2699 -
2700 - if (decision === "accept" || decision === "acceptForSession") {
2701 - return {
2702 - behavior: "allow",
2703 - updatedInput: toolInput,
2704 - ...(decision === "acceptForSession" && pendingApproval.suggestions
2705 - ? { updatedPermissions: [...pendingApproval.suggestions] }
2706 - : {}),
2707 - } satisfies PermissionResult;
2708 - }
2709 -
2710 - return {
2711 - behavior: "deny",
2712 - message:
2713 - decision === "cancel"
2714 - ? "User cancelled tool execution."
2715 - : "User declined tool execution.",
2716 - } satisfies PermissionResult;
2717 - }),
2718 - );
2308 + // @effect-diagnostics-next-line tryCatchInEffectGen:off
2309 + try {
2310 + context.query.close();
2311 + } catch (cause) {
2312 + yield* emitRuntimeError(context, "Failed to close Claude runtime query.", cause);
2313 + }
2314
2720 - const claudeSettings = yield* serverSettingsService.getSettings.pipe(
2721 - Effect.map((settings) => settings.providers.claudeAgent),
2722 - Effect.mapError(
2723 - (error) =>
2724 - new ProviderAdapterProcessError({
2725 - provider: PROVIDER,
2726 - threadId: input.threadId,
2727 - detail: error.message,
2728 - cause: error,
2729 - }),
2730 - ),
2731 - );
2732 - const claudeBinaryPath = claudeSettings.binaryPath;
2733 - const modelSelection =
2734 - input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
2735 - const caps = getClaudeModelCapabilities(modelSelection?.model);
2736 - const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
2737 - const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
2738 - null) as ClaudeCodeEffort | null;
2739 - const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
2740 - const thinking =
2741 - typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
2742 - ? modelSelection.options.thinking
2743 - : undefined;
2744 - const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
2745 - const permissionMode =
2746 - input.runtimeMode === "full-access" ? "bypassPermissions" : undefined;
2747 - const settings = {
2748 - ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
2749 - ...(fastMode ? { fastMode: true } : {}),
2750 - };
2315 + const updatedAt = yield* nowIso;
2316 + context.session = {
2317 + ...context.session,
2318 + status: "closed",
2319 + activeTurnId: undefined,
2320 + updatedAt,
2321 + };
2322
2752 - const queryOptions: ClaudeQueryOptions = {
2753 - ...(input.cwd ? { cwd: input.cwd } : {}),
2754 - ...(apiModelId ? { model: apiModelId } : {}),
2755 - pathToClaudeCodeExecutable: claudeBinaryPath,
2756 - settingSources: [...CLAUDE_SETTING_SOURCES],
2757 - ...(effectiveEffort ? { effort: effectiveEffort } : {}),
2758 - ...(permissionMode ? { permissionMode } : {}),
2759 - ...(permissionMode === "bypassPermissions"
2760 - ? { allowDangerouslySkipPermissions: true }
2761 - : {}),
2762 - ...(Object.keys(settings).length > 0 ? { settings } : {}),
2763 - ...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}),
2764 - ...(newSessionId ? { sessionId: newSessionId } : {}),
2765 - includePartialMessages: true,
2766 - canUseTool,
2767 - env: process.env,
2768 - ...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
2769 - };
2323 + if (options?.emitExitEvent !== false) {
2324 + const stamp = yield* makeEventStamp();
2325 + yield* offerRuntimeEvent({
2326 + type: "session.exited",
2327 + eventId: stamp.eventId,
2328 + provider: PROVIDER,
2329 + createdAt: stamp.createdAt,
2330 + threadId: context.session.threadId,
2331 + payload: {
2332 + reason: "Session stopped",
2333 + exitKind: "graceful",
2334 + },
2335 + providerRefs: {},
2336 + });
2337 + }
2338
2771 - const queryRuntime = yield* Effect.try({
2772 - try: () =>
2773 - createQuery({
2774 - prompt,
2775 - options: queryOptions,
2776 - }),
2777 - catch: (cause) =>
2778 - new ProviderAdapterProcessError({
2779 - provider: PROVIDER,
2780 - threadId,
2781 - detail: toMessage(cause, "Failed to start Claude runtime session."),
2782 - cause,
2783 - }),
2784 - });
2339 + sessions.delete(context.session.threadId);
2340 + });
2341
2786 - const session: ProviderSession = {
2342 + const requireSession = (
2343 + threadId: ThreadId,
2344 + ): Effect.Effect<ClaudeSessionContext, ProviderAdapterError> => {
2345 + const context = sessions.get(threadId);
2346 + if (!context) {
2347 + return Effect.fail(
2348 + new ProviderAdapterSessionNotFoundError({
2349 + provider: PROVIDER,
2350 threadId,
2351 + }),
2352 + );
2353 + }
2354 + if (context.stopped || context.session.status === "closed") {
2355 + return Effect.fail(
2356 + new ProviderAdapterSessionClosedError({
2357 provider: PROVIDER,
2789 - status: "ready",
2790 - runtimeMode: input.runtimeMode,
2791 - ...(input.cwd ? { cwd: input.cwd } : {}),
2792 - ...(modelSelection?.model ? { model: modelSelection.model } : {}),
2793 - ...(threadId ? { threadId } : {}),
2794 - resumeCursor: {
2795 - ...(threadId ? { threadId } : {}),
2796 - ...(sessionId ? { resume: sessionId } : {}),
2797 - ...(resumeState?.resumeSessionAt
2798 - ? { resumeSessionAt: resumeState.resumeSessionAt }
2799 - : {}),
2800 - turnCount: resumeState?.turnCount ?? 0,
2801 - },
2802 - createdAt: startedAt,
2803 - updatedAt: startedAt,
2804 - };
2805 -
2806 - const context: ClaudeSessionContext = {
2807 - session,
2808 - promptQueue,
2809 - query: queryRuntime,
2810 - streamFiber: undefined,
2811 - startedAt,
2812 - basePermissionMode: permissionMode,
2813 - currentApiModelId: apiModelId,
2814 - resumeSessionId: sessionId,
2815 - pendingApprovals,
2816 - pendingUserInputs,
2817 - turns: [],
2818 - inFlightTools,
2819 - turnState: undefined,
2820 - lastKnownContextWindow: undefined,
2821 - lastKnownTokenUsage: undefined,
2822 - lastAssistantUuid: resumeState?.resumeSessionAt,
2823 - lastThreadStartedId: undefined,
2824 - stopped: false,
2825 - };
2826 - yield* Ref.set(contextRef, context);
2827 - sessions.set(threadId, context);
2358 + threadId,
2359 + }),
2360 + );
2361 + }
2362 + return Effect.succeed(context);
2363 + };
2364
2829 - const sessionStartedStamp = yield* makeEventStamp();
2830 - yield* offerRuntimeEvent({
2831 - type: "session.started",
2832 - eventId: sessionStartedStamp.eventId,
2365 + const startSession: ClaudeAdapterShape["startSession"] = Effect.fn("startSession")(
2366 + function* (input) {
2367 + if (input.provider !== undefined && input.provider !== PROVIDER) {
2368 + return yield* new ProviderAdapterValidationError({
2369 provider: PROVIDER,
2834 - createdAt: sessionStartedStamp.createdAt,
2835 - threadId,
2836 - payload: input.resumeCursor !== undefined ? { resume: input.resumeCursor } : {},
2837 - providerRefs: {},
2370 + operation: "startSession",
2371 + issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
2372 });
2373 + }
2374 +
2375 + const startedAt = yield* nowIso;
2376 + const resumeState = readClaudeResumeState(input.resumeCursor);
2377 + const threadId = input.threadId;
2378 + const existingResumeSessionId = resumeState?.resume;
2379 + const newSessionId =
2380 + existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined;
2381 + const sessionId = existingResumeSessionId ?? newSessionId;
2382 +
2383 + const promptQueue = yield* Queue.unbounded<PromptQueueItem>();
2384 + const prompt = Stream.fromQueue(promptQueue).pipe(
2385 + Stream.filter((item) => item.type === "message"),
2386 + Stream.map((item) => item.message),
2387 + Stream.catchCause((cause) =>
2388 + Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
2389 + ),
2390 + Stream.toAsyncIterable,
2391 + );
2392
2840 - const configuredStamp = yield* makeEventStamp();
2393 + const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
2394 + const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
2395 + const inFlightTools = new Map<number, ToolInFlight>();
2396 +
2397 + const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);
2398 +
2399 + /**
2400 + * Handle AskUserQuestion tool calls by emitting a `user-input.requested`
2401 + * runtime event and waiting for the user to respond via `respondToUserInput`.
2402 + */
2403 + const handleAskUserQuestion = Effect.fn("handleAskUserQuestion")(function* (
2404 + context: ClaudeSessionContext,
2405 + toolInput: Record<string, unknown>,
2406 + callbackOptions: { readonly signal: AbortSignal; readonly toolUseID?: string },
2407 + ) {
2408 + const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4);
2409 +
2410 + // Parse questions from the SDK's AskUserQuestion input.
2411 + const rawQuestions = Array.isArray(toolInput.questions) ? toolInput.questions : [];
2412 + const questions: Array<UserInputQuestion> = rawQuestions.map(
2413 + (q: Record<string, unknown>, idx: number) => ({
2414 + id: typeof q.header === "string" ? q.header : `q-${idx}`,
2415 + header: typeof q.header === "string" ? q.header : `Question ${idx + 1}`,
2416 + question: typeof q.question === "string" ? q.question : "",
2417 + options: Array.isArray(q.options)
2418 + ? q.options.map((opt: Record<string, unknown>) => ({
2419 + label: typeof opt.label === "string" ? opt.label : "",
2420 + description: typeof opt.description === "string" ? opt.description : "",
2421 + }))
2422 + : [],
2423 + multiSelect: typeof q.multiSelect === "boolean" ? q.multiSelect : false,
2424 + }),
2425 + );
2426 +
2427 + const answersDeferred = yield* Deferred.make<ProviderUserInputAnswers>();
2428 + let aborted = false;
2429 + const pendingInput: PendingUserInput = {
2430 + questions,
2431 + answers: answersDeferred,
2432 + };
2433 +
2434 + // Emit user-input.requested so the UI can present the questions.
2435 + const requestedStamp = yield* makeEventStamp();
2436 yield* offerRuntimeEvent({
2842 - type: "session.configured",
2843 - eventId: configuredStamp.eventId,
2437 + type: "user-input.requested",
2438 + eventId: requestedStamp.eventId,
2439 provider: PROVIDER,
2845 - createdAt: configuredStamp.createdAt,
2846 - threadId,
2847 - payload: {
2848 - config: {
2849 - ...(apiModelId ? { model: apiModelId } : {}),
2850 - ...(input.cwd ? { cwd: input.cwd } : {}),
2851 - ...(effectiveEffort ? { effort: effectiveEffort } : {}),
2852 - ...(permissionMode ? { permissionMode } : {}),
2853 - ...(fastMode ? { fastMode: true } : {}),
2854 - },
2440 + createdAt: requestedStamp.createdAt,
2441 + threadId: context.session.threadId,
2442 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
2443 + requestId: asRuntimeRequestId(requestId),
2444 + payload: { questions },
2445 + providerRefs: nativeProviderRefs(context, {
2446 + providerItemId: callbackOptions.toolUseID,
2447 + }),
2448 + raw: {
2449 + source: "claude.sdk.permission",
2450 + method: "canUseTool/AskUserQuestion",
2451 + payload: { toolName: "AskUserQuestion", input: toolInput },
2452 },
2856 - providerRefs: {},
2453 });
2454
2859 - const readyStamp = yield* makeEventStamp();
2455 + pendingUserInputs.set(requestId, pendingInput);
2456 +
2457 + // Handle abort (e.g. turn interrupted while waiting for user input).
2458 + const onAbort = () => {
2459 + if (!pendingUserInputs.has(requestId)) {
2460 + return;
2461 + }
2462 + aborted = true;
2463 + pendingUserInputs.delete(requestId);
2464 + Effect.runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers));
2465 + };
2466 + callbackOptions.signal.addEventListener("abort", onAbort, { once: true });
2467 +
2468 + // Block until the user provides answers.
2469 + const answers = yield* Deferred.await(answersDeferred);
2470 + pendingUserInputs.delete(requestId);
2471 +
2472 + // Emit user-input.resolved so the UI knows the interaction completed.
2473 + const resolvedStamp = yield* makeEventStamp();
2474 yield* offerRuntimeEvent({
2861 - type: "session.state.changed",
2862 - eventId: readyStamp.eventId,
2475 + type: "user-input.resolved",
2476 + eventId: resolvedStamp.eventId,
2477 provider: PROVIDER,
2864 - createdAt: readyStamp.createdAt,
2865 - threadId,
2866 - payload: {
2867 - state: "ready",
2478 + createdAt: resolvedStamp.createdAt,
2479 + threadId: context.session.threadId,
2480 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
2481 + requestId: asRuntimeRequestId(requestId),
2482 + payload: { answers },
2483 + providerRefs: nativeProviderRefs(context, {
2484 + providerItemId: callbackOptions.toolUseID,
2485 + }),
2486 + raw: {
2487 + source: "claude.sdk.permission",
2488 + method: "canUseTool/AskUserQuestion/resolved",
2489 + payload: { answers },
2490 },
2869 - providerRefs: {},
2491 });
2492
2872 - const streamFiber = Effect.runFork(runSdkStream(context));
2873 - context.streamFiber = streamFiber;
2874 - streamFiber.addObserver((exit) => {
2875 - if (context.stopped) {
2876 - return;
2877 - }
2878 - if (context.streamFiber === streamFiber) {
2879 - context.streamFiber = undefined;
2880 - }
2881 - Effect.runFork(handleStreamExit(context, exit));
2882 - });
2493 + if (aborted) {
2494 + return {
2495 + behavior: "deny",
2496 + message: "User cancelled tool execution.",
2497 + } satisfies PermissionResult;
2498 + }
2499
2500 + // Return the answers to the SDK in the expected format:
2501 + // { questions: [...], answers: { questionText: selectedLabel } }
2502 return {
2885 - ...session,
2886 - };
2503 + behavior: "allow",
2504 + updatedInput: {
2505 + questions: toolInput.questions,
2506 + answers,
2507 + },
2508 + } satisfies PermissionResult;
2509 });
2510
2889 - const sendTurn: ClaudeAdapterShape["sendTurn"] = (input) =>
2890 - Effect.gen(function* () {
2891 - const context = yield* requireSession(input.threadId);
2892 - const modelSelection =
2893 - input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
2511 + const canUseToolEffect = Effect.fn("canUseTool")(function* (
2512 + toolName: Parameters<CanUseTool>[0],
2513 + toolInput: Parameters<CanUseTool>[1],
2514 + callbackOptions: Parameters<CanUseTool>[2],
2515 + ) {
2516 + const context = yield* Ref.get(contextRef);
2517 + if (!context) {
2518 + return {
2519 + behavior: "deny",
2520 + message: "Claude session context is unavailable.",
2521 + } satisfies PermissionResult;
2522 + }
2523
2895 - if (context.turnState) {
2896 - // Auto-close a stale synthetic turn (from background agent responses
2897 - // between user prompts) to prevent blocking the user's next turn.
2898 - yield* completeTurn(context, "completed");
2524 + // Handle AskUserQuestion: surface clarifying questions to the
2525 + // user via the user-input runtime event channel, regardless of
2526 + // runtime mode (plan mode relies on this heavily).
2527 + if (toolName === "AskUserQuestion") {
2528 + return yield* handleAskUserQuestion(context, toolInput, callbackOptions);
2529 }
2530
2901 - if (modelSelection?.model) {
2902 - const apiModelId = resolveApiModelId(modelSelection);
2903 - if (context.currentApiModelId !== apiModelId) {
2904 - yield* Effect.tryPromise({
2905 - try: () => context.query.setModel(apiModelId),
2906 - catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause),
2531 + if (toolName === "ExitPlanMode") {
2532 + const planMarkdown = extractExitPlanModePlan(toolInput);
2533 + if (planMarkdown) {
2534 + yield* emitProposedPlanCompleted(context, {
2535 + planMarkdown,
2536 + toolUseId: callbackOptions.toolUseID,
2537 + rawSource: "claude.sdk.permission",
2538 + rawMethod: "canUseTool/ExitPlanMode",
2539 + rawPayload: {
2540 + toolName,
2541 + input: toolInput,
2542 + },
2543 });
2908 - context.currentApiModelId = apiModelId;
2544 }
2910 - context.session = {
2911 - ...context.session,
2912 - model: modelSelection.model,
2913 - };
2914 - }
2545
2916 - // Apply interaction mode by switching the SDK's permission mode.
2917 - // "plan" maps directly to the SDK's "plan" permission mode;
2918 - // "default" restores the session's original permission mode.
2919 - // When interactionMode is absent we leave the current mode unchanged.
2920 - if (input.interactionMode === "plan") {
2921 - yield* Effect.tryPromise({
2922 - try: () => context.query.setPermissionMode("plan"),
2923 - catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause),
2924 - });
2925 - } else if (input.interactionMode === "default") {
2926 - yield* Effect.tryPromise({
2927 - try: () =>
2928 - context.query.setPermissionMode(context.basePermissionMode ?? "bypassPermissions"),
2929 - catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause),
2930 - });
2546 + return {
2547 + behavior: "deny",
2548 + message:
2549 + "The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
2550 + } satisfies PermissionResult;
2551 }
2552
2933 - const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4);
2934 - const turnState: ClaudeTurnState = {
2935 - turnId,
2936 - startedAt: yield* nowIso,
2937 - items: [],
2938 - assistantTextBlocks: new Map(),
2939 - assistantTextBlockOrder: [],
2940 - capturedProposedPlanKeys: new Set(),
2941 - nextSyntheticAssistantBlockIndex: -1,
2942 - };
2553 + const runtimeMode = input.runtimeMode ?? "full-access";
2554 + if (runtimeMode === "full-access") {
2555 + return {
2556 + behavior: "allow",
2557 + updatedInput: toolInput,
2558 + } satisfies PermissionResult;
2559 + }
2560
2944 - const updatedAt = yield* nowIso;
2945 - context.turnState = turnState;
2946 - context.session = {
2947 - ...context.session,
2948 - status: "running",
2949 - activeTurnId: turnId,
2950 - updatedAt,
2561 + const requestId = ApprovalRequestId.makeUnsafe(yield* Random.nextUUIDv4);
2562 + const requestType = classifyRequestType(toolName);
2563 + const detail = summarizeToolRequest(toolName, toolInput);
2564 + const decisionDeferred = yield* Deferred.make<ProviderApprovalDecision>();
2565 + const pendingApproval: PendingApproval = {
2566 + requestType,
2567 + detail,
2568 + decision: decisionDeferred,
2569 + ...(callbackOptions.suggestions ? { suggestions: callbackOptions.suggestions } : {}),
2570 };
2571
2953 - const turnStartedStamp = yield* makeEventStamp();
2572 + const requestedStamp = yield* makeEventStamp();
2573 yield* offerRuntimeEvent({
2955 - type: "turn.started",
2956 - eventId: turnStartedStamp.eventId,
2574 + type: "request.opened",
2575 + eventId: requestedStamp.eventId,
2576 provider: PROVIDER,
2958 - createdAt: turnStartedStamp.createdAt,
2577 + createdAt: requestedStamp.createdAt,
2578 threadId: context.session.threadId,
2960 - turnId,
2961 - payload: modelSelection?.model ? { model: modelSelection.model } : {},
2962 - providerRefs: {},
2579 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
2580 + requestId: asRuntimeRequestId(requestId),
2581 + payload: {
2582 + requestType,
2583 + detail,
2584 + args: {
2585 + toolName,
2586 + input: toolInput,
2587 + ...(callbackOptions.toolUseID ? { toolUseId: callbackOptions.toolUseID } : {}),
2588 + },
2589 + },
2590 + providerRefs: nativeProviderRefs(context, {
2591 + providerItemId: callbackOptions.toolUseID,
2592 + }),
2593 + raw: {
2594 + source: "claude.sdk.permission",
2595 + method: "canUseTool/request",
2596 + payload: {
2597 + toolName,
2598 + input: toolInput,
2599 + },
2600 + },
2601 });
2602
2965 - const message = yield* buildUserMessageEffect(input, {
2966 - fileSystem,
2967 - attachmentsDir: serverConfig.attachmentsDir,
2603 + pendingApprovals.set(requestId, pendingApproval);
2604 +
2605 + const onAbort = () => {
2606 + if (!pendingApprovals.has(requestId)) {
2607 + return;
2608 + }
2609 + pendingApprovals.delete(requestId);
2610 + Effect.runFork(Deferred.succeed(decisionDeferred, "cancel"));
2611 + };
2612 +
2613 + callbackOptions.signal.addEventListener("abort", onAbort, {
2614 + once: true,
2615 });
2616
2970 - yield* Queue.offer(context.promptQueue, {
2971 - type: "message",
2972 - message,
2973 - }).pipe(Effect.mapError((cause) => toRequestError(input.threadId, "turn/start", cause)));
2617 + const decision = yield* Deferred.await(decisionDeferred);
2618 + pendingApprovals.delete(requestId);
2619
2975 - return {
2620 + const resolvedStamp = yield* makeEventStamp();
2621 + yield* offerRuntimeEvent({
2622 + type: "request.resolved",
2623 + eventId: resolvedStamp.eventId,
2624 + provider: PROVIDER,
2625 + createdAt: resolvedStamp.createdAt,
2626 threadId: context.session.threadId,
2977 - turnId,
2978 - ...(context.session.resumeCursor !== undefined
2979 - ? { resumeCursor: context.session.resumeCursor }
2980 - : {}),
2981 - };
2627 + ...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
2628 + requestId: asRuntimeRequestId(requestId),
2629 + payload: {
2630 + requestType,
2631 + decision,
2632 + },
2633 + providerRefs: nativeProviderRefs(context, {
2634 + providerItemId: callbackOptions.toolUseID,
2635 + }),
2636 + raw: {
2637 + source: "claude.sdk.permission",
2638 + method: "canUseTool/decision",
2639 + payload: {
2640 + decision,
2641 + },
2642 + },
2643 + });
2644 +
2645 + if (decision === "accept" || decision === "acceptForSession") {
2646 + return {
2647 + behavior: "allow",
2648 + updatedInput: toolInput,
2649 + ...(decision === "acceptForSession" && pendingApproval.suggestions
2650 + ? { updatedPermissions: [...pendingApproval.suggestions] }
2651 + : {}),
2652 + } satisfies PermissionResult;
2653 + }
2654 +
2655 + return {
2656 + behavior: "deny",
2657 + message:
2658 + decision === "cancel"
2659 + ? "User cancelled tool execution."
2660 + : "User declined tool execution.",
2661 + } satisfies PermissionResult;
2662 });
2663
2984 - const interruptTurn: ClaudeAdapterShape["interruptTurn"] = (threadId, _turnId) =>
2985 - Effect.gen(function* () {
2986 - const context = yield* requireSession(threadId);
2987 - yield* Effect.tryPromise({
2988 - try: () => context.query.interrupt(),
2989 - catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
2990 - });
2664 + const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) =>
2665 + Effect.runPromise(canUseToolEffect(toolName, toolInput, callbackOptions));
2666 +
2667 + const claudeSettings = yield* serverSettingsService.getSettings.pipe(
2668 + Effect.map((settings) => settings.providers.claudeAgent),
2669 + Effect.mapError(
2670 + (error) =>
2671 + new ProviderAdapterProcessError({
2672 + provider: PROVIDER,
2673 + threadId: input.threadId,
2674 + detail: error.message,
2675 + cause: error,
2676 + }),
2677 + ),
2678 + );
2679 + const claudeBinaryPath = claudeSettings.binaryPath;
2680 + const modelSelection =
2681 + input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
2682 + const caps = getClaudeModelCapabilities(modelSelection?.model);
2683 + const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
2684 + const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
2685 + null) as ClaudeCodeEffort | null;
2686 + const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
2687 + const thinking =
2688 + typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
2689 + ? modelSelection.options.thinking
2690 + : undefined;
2691 + const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
2692 + const permissionMode = input.runtimeMode === "full-access" ? "bypassPermissions" : undefined;
2693 + const settings = {
2694 + ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
2695 + ...(fastMode ? { fastMode: true } : {}),
2696 + };
2697 +
2698 + const queryOptions: ClaudeQueryOptions = {
2699 + ...(input.cwd ? { cwd: input.cwd } : {}),
2700 + ...(apiModelId ? { model: apiModelId } : {}),
2701 + pathToClaudeCodeExecutable: claudeBinaryPath,
2702 + settingSources: [...CLAUDE_SETTING_SOURCES],
2703 + ...(effectiveEffort ? { effort: effectiveEffort } : {}),
2704 + ...(permissionMode ? { permissionMode } : {}),
2705 + ...(permissionMode === "bypassPermissions"
2706 + ? { allowDangerouslySkipPermissions: true }
2707 + : {}),
2708 + ...(Object.keys(settings).length > 0 ? { settings } : {}),
2709 + ...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}),
2710 + ...(newSessionId ? { sessionId: newSessionId } : {}),
2711 + includePartialMessages: true,
2712 + canUseTool,
2713 + env: process.env,
2714 + ...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
2715 + };
2716 +
2717 + const queryRuntime = yield* Effect.try({
2718 + try: () =>
2719 + createQuery({
2720 + prompt,
2721 + options: queryOptions,
2722 + }),
2723 + catch: (cause) =>
2724 + new ProviderAdapterProcessError({
2725 + provider: PROVIDER,
2726 + threadId,
2727 + detail: toMessage(cause, "Failed to start Claude runtime session."),
2728 + cause,
2729 + }),
2730 + });
2731 +
2732 + const session: ProviderSession = {
2733 + threadId,
2734 + provider: PROVIDER,
2735 + status: "ready",
2736 + runtimeMode: input.runtimeMode,
2737 + ...(input.cwd ? { cwd: input.cwd } : {}),
2738 + ...(modelSelection?.model ? { model: modelSelection.model } : {}),
2739 + ...(threadId ? { threadId } : {}),
2740 + resumeCursor: {
2741 + ...(threadId ? { threadId } : {}),
2742 + ...(sessionId ? { resume: sessionId } : {}),
2743 + ...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}),
2744 + turnCount: resumeState?.turnCount ?? 0,
2745 + },
2746 + createdAt: startedAt,
2747 + updatedAt: startedAt,
2748 + };
2749 +
2750 + const context: ClaudeSessionContext = {
2751 + session,
2752 + promptQueue,
2753 + query: queryRuntime,
2754 + streamFiber: undefined,
2755 + startedAt,
2756 + basePermissionMode: permissionMode,
2757 + currentApiModelId: apiModelId,
2758 + resumeSessionId: sessionId,
2759 + pendingApprovals,
2760 + pendingUserInputs,
2761 + turns: [],
2762 + inFlightTools,
2763 + turnState: undefined,
2764 + lastKnownContextWindow: undefined,
2765 + lastKnownTokenUsage: undefined,
2766 + lastAssistantUuid: resumeState?.resumeSessionAt,
2767 + lastThreadStartedId: undefined,
2768 + stopped: false,
2769 + };
2770 + yield* Ref.set(contextRef, context);
2771 + sessions.set(threadId, context);
2772 +
2773 + const sessionStartedStamp = yield* makeEventStamp();
2774 + yield* offerRuntimeEvent({
2775 + type: "session.started",
2776 + eventId: sessionStartedStamp.eventId,
2777 + provider: PROVIDER,
2778 + createdAt: sessionStartedStamp.createdAt,
2779 + threadId,
2780 + payload: input.resumeCursor !== undefined ? { resume: input.resumeCursor } : {},
2781 + providerRefs: {},
2782 });
2783
2993 - const readThread: ClaudeAdapterShape["readThread"] = (threadId) =>
2994 - Effect.gen(function* () {
2995 - const context = yield* requireSession(threadId);
2996 - return yield* snapshotThread(context);
2784 + const configuredStamp = yield* makeEventStamp();
2785 + yield* offerRuntimeEvent({
2786 + type: "session.configured",
2787 + eventId: configuredStamp.eventId,
2788 + provider: PROVIDER,
2789 + createdAt: configuredStamp.createdAt,
2790 + threadId,
2791 + payload: {
2792 + config: {
2793 + ...(apiModelId ? { model: apiModelId } : {}),
2794 + ...(input.cwd ? { cwd: input.cwd } : {}),
2795 + ...(effectiveEffort ? { effort: effectiveEffort } : {}),
2796 + ...(permissionMode ? { permissionMode } : {}),
2797 + ...(fastMode ? { fastMode: true } : {}),
2798 + },
2799 + },
2800 + providerRefs: {},
2801 });
2802
2999 - const rollbackThread: ClaudeAdapterShape["rollbackThread"] = (threadId, numTurns) =>
3000 - Effect.gen(function* () {
3001 - const context = yield* requireSession(threadId);
3002 - const nextLength = Math.max(0, context.turns.length - numTurns);
3003 - context.turns.splice(nextLength);
3004 - yield* updateResumeCursor(context);
3005 - return yield* snapshotThread(context);
2803 + const readyStamp = yield* makeEventStamp();
2804 + yield* offerRuntimeEvent({
2805 + type: "session.state.changed",
2806 + eventId: readyStamp.eventId,
2807 + provider: PROVIDER,
2808 + createdAt: readyStamp.createdAt,
2809 + threadId,
2810 + payload: {
2811 + state: "ready",
2812 + },
2813 + providerRefs: {},
2814 });
2815
3008 - const respondToRequest: ClaudeAdapterShape["respondToRequest"] = (
3009 - threadId,
3010 - requestId,
3011 - decision,
3012 - ) =>
3013 - Effect.gen(function* () {
3014 - const context = yield* requireSession(threadId);
3015 - const pending = context.pendingApprovals.get(requestId);
3016 - if (!pending) {
3017 - return yield* new ProviderAdapterRequestError({
3018 - provider: PROVIDER,
3019 - method: "item/requestApproval/decision",
3020 - detail: `Unknown pending approval request: ${requestId}`,
3021 - });
2816 + const streamFiber = Effect.runFork(runSdkStream(context));
2817 + context.streamFiber = streamFiber;
2818 + streamFiber.addObserver((exit) => {
2819 + if (context.stopped) {
2820 + return;
2821 }
2822 + if (context.streamFiber === streamFiber) {
2823 + context.streamFiber = undefined;
2824 + }
2825 + Effect.runFork(handleStreamExit(context, exit));
2826 + });
2827 +
2828 + return {
2829 + ...session,
2830 + };
2831 + },
2832 + );
2833 +
2834 + const sendTurn: ClaudeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
2835 + const context = yield* requireSession(input.threadId);
2836 + const modelSelection =
2837 + input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
2838
3024 - context.pendingApprovals.delete(requestId);
3025 - yield* Deferred.succeed(pending.decision, decision);
2839 + if (context.turnState) {
2840 + // Auto-close a stale synthetic turn (from background agent responses
2841 + // between user prompts) to prevent blocking the user's next turn.
2842 + yield* completeTurn(context, "completed");
2843 + }
2844 +
2845 + if (modelSelection?.model) {
2846 + const apiModelId = resolveApiModelId(modelSelection);
2847 + if (context.currentApiModelId !== apiModelId) {
2848 + yield* Effect.tryPromise({
2849 + try: () => context.query.setModel(apiModelId),
2850 + catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause),
2851 + });
2852 + context.currentApiModelId = apiModelId;
2853 + }
2854 + context.session = {
2855 + ...context.session,
2856 + model: modelSelection.model,
2857 + };
2858 + }
2859 +
2860 + // Apply interaction mode by switching the SDK's permission mode.
2861 + // "plan" maps directly to the SDK's "plan" permission mode;
2862 + // "default" restores the session's original permission mode.
2863 + // When interactionMode is absent we leave the current mode unchanged.
2864 + if (input.interactionMode === "plan") {
2865 + yield* Effect.tryPromise({
2866 + try: () => context.query.setPermissionMode("plan"),
2867 + catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause),
2868 + });
2869 + } else if (input.interactionMode === "default") {
2870 + yield* Effect.tryPromise({
2871 + try: () =>
2872 + context.query.setPermissionMode(context.basePermissionMode ?? "bypassPermissions"),
2873 + catch: (cause) => toRequestError(input.threadId, "turn/setPermissionMode", cause),
2874 });
2875 + }
2876
3028 - const respondToUserInput: ClaudeAdapterShape["respondToUserInput"] = (
3029 - threadId,
3030 - requestId,
3031 - answers,
3032 - ) =>
3033 - Effect.gen(function* () {
3034 - const context = yield* requireSession(threadId);
3035 - const pending = context.pendingUserInputs.get(requestId);
3036 - if (!pending) {
3037 - return yield* new ProviderAdapterRequestError({
3038 - provider: PROVIDER,
3039 - method: "item/tool/respondToUserInput",
3040 - detail: `Unknown pending user-input request: ${requestId}`,
3041 - });
3042 - }
2877 + const turnId = TurnId.makeUnsafe(yield* Random.nextUUIDv4);
2878 + const turnState: ClaudeTurnState = {
2879 + turnId,
2880 + startedAt: yield* nowIso,
2881 + items: [],
2882 + assistantTextBlocks: new Map(),
2883 + assistantTextBlockOrder: [],
2884 + capturedProposedPlanKeys: new Set(),
2885 + nextSyntheticAssistantBlockIndex: -1,
2886 + };
2887 +
2888 + const updatedAt = yield* nowIso;
2889 + context.turnState = turnState;
2890 + context.session = {
2891 + ...context.session,
2892 + status: "running",
2893 + activeTurnId: turnId,
2894 + updatedAt,
2895 + };
2896 +
2897 + const turnStartedStamp = yield* makeEventStamp();
2898 + yield* offerRuntimeEvent({
2899 + type: "turn.started",
2900 + eventId: turnStartedStamp.eventId,
2901 + provider: PROVIDER,
2902 + createdAt: turnStartedStamp.createdAt,
2903 + threadId: context.session.threadId,
2904 + turnId,
2905 + payload: modelSelection?.model ? { model: modelSelection.model } : {},
2906 + providerRefs: {},
2907 + });
2908 +
2909 + const message = yield* buildUserMessageEffect(input, {
2910 + fileSystem,
2911 + attachmentsDir: serverConfig.attachmentsDir,
2912 + });
2913 +
2914 + yield* Queue.offer(context.promptQueue, {
2915 + type: "message",
2916 + message,
2917 + }).pipe(Effect.mapError((cause) => toRequestError(input.threadId, "turn/start", cause)));
2918 +
2919 + return {
2920 + threadId: context.session.threadId,
2921 + turnId,
2922 + ...(context.session.resumeCursor !== undefined
2923 + ? { resumeCursor: context.session.resumeCursor }
2924 + : {}),
2925 + };
2926 + });
2927
3044 - context.pendingUserInputs.delete(requestId);
3045 - yield* Deferred.succeed(pending.answers, answers);
2928 + const interruptTurn: ClaudeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
2929 + function* (threadId, _turnId) {
2930 + const context = yield* requireSession(threadId);
2931 + yield* Effect.tryPromise({
2932 + try: () => context.query.interrupt(),
2933 + catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
2934 });
2935 + },
2936 + );
2937
3048 - const stopSession: ClaudeAdapterShape["stopSession"] = (threadId) =>
3049 - Effect.gen(function* () {
3050 - const context = yield* requireSession(threadId);
3051 - yield* stopSessionInternal(context, {
3052 - emitExitEvent: true,
2938 + const readThread: ClaudeAdapterShape["readThread"] = Effect.fn("readThread")(
2939 + function* (threadId) {
2940 + const context = yield* requireSession(threadId);
2941 + return yield* snapshotThread(context);
2942 + },
2943 + );
2944 +
2945 + const rollbackThread: ClaudeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(
2946 + function* (threadId, numTurns) {
2947 + const context = yield* requireSession(threadId);
2948 + const nextLength = Math.max(0, context.turns.length - numTurns);
2949 + context.turns.splice(nextLength);
2950 + yield* updateResumeCursor(context);
2951 + return yield* snapshotThread(context);
2952 + },
2953 + );
2954 +
2955 + const respondToRequest: ClaudeAdapterShape["respondToRequest"] = Effect.fn("respondToRequest")(
2956 + function* (threadId, requestId, decision) {
2957 + const context = yield* requireSession(threadId);
2958 + const pending = context.pendingApprovals.get(requestId);
2959 + if (!pending) {
2960 + return yield* new ProviderAdapterRequestError({
2961 + provider: PROVIDER,
2962 + method: "item/requestApproval/decision",
2963 + detail: `Unknown pending approval request: ${requestId}`,
2964 });
2965 + }
2966 +
2967 + context.pendingApprovals.delete(requestId);
2968 + yield* Deferred.succeed(pending.decision, decision);
2969 + },
2970 + );
2971 +
2972 + const respondToUserInput: ClaudeAdapterShape["respondToUserInput"] = Effect.fn(
2973 + "respondToUserInput",
2974 + )(function* (threadId, requestId, answers) {
2975 + const context = yield* requireSession(threadId);
2976 + const pending = context.pendingUserInputs.get(requestId);
2977 + if (!pending) {
2978 + return yield* new ProviderAdapterRequestError({
2979 + provider: PROVIDER,
2980 + method: "item/tool/respondToUserInput",
2981 + detail: `Unknown pending user-input request: ${requestId}`,
2982 });
2983 + }
2984
3056 - const listSessions: ClaudeAdapterShape["listSessions"] = () =>
3057 - Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session })));
2985 + context.pendingUserInputs.delete(requestId);
2986 + yield* Deferred.succeed(pending.answers, answers);
2987 + });
2988
3059 - const hasSession: ClaudeAdapterShape["hasSession"] = (threadId) =>
3060 - Effect.sync(() => {
3061 - const context = sessions.get(threadId);
3062 - return context !== undefined && !context.stopped;
2989 + const stopSession: ClaudeAdapterShape["stopSession"] = Effect.fn("stopSession")(
2990 + function* (threadId) {
2991 + const context = yield* requireSession(threadId);
2992 + yield* stopSessionInternal(context, {
2993 + emitExitEvent: true,
2994 });
2995 + },
2996 + );
2997
3065 - const stopAll: ClaudeAdapterShape["stopAll"] = () =>
3066 - Effect.forEach(
3067 - sessions,
3068 - ([, context]) =>
3069 - stopSessionInternal(context, {
3070 - emitExitEvent: true,
3071 - }),
3072 - { discard: true },
3073 - );
2998 + const listSessions: ClaudeAdapterShape["listSessions"] = () =>
2999 + Effect.sync(() => Array.from(sessions.values(), ({ session }) => ({ ...session })));
3000
3075 - yield* Effect.addFinalizer(() =>
3076 - Effect.forEach(
3077 - sessions,
3078 - ([, context]) =>
3079 - stopSessionInternal(context, {
3080 - emitExitEvent: false,
3081 - }),
3082 - { discard: true },
3083 - ).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))),
3001 + const hasSession: ClaudeAdapterShape["hasSession"] = (threadId) =>
3002 + Effect.sync(() => {
3003 + const context = sessions.get(threadId);
3004 + return context !== undefined && !context.stopped;
3005 + });
3006 +
3007 + const stopAll: ClaudeAdapterShape["stopAll"] = () =>
3008 + Effect.forEach(
3009 + sessions,
3010 + ([, context]) =>
3011 + stopSessionInternal(context, {
3012 + emitExitEvent: true,
3013 + }),
3014 + { discard: true },
3015 );
3016
3086 - return {
3087 - provider: PROVIDER,
3088 - capabilities: {
3089 - sessionModelSwitch: "in-session",
3090 - },
3091 - startSession,
3092 - sendTurn,
3093 - interruptTurn,
3094 - readThread,
3095 - rollbackThread,
3096 - respondToRequest,
3097 - respondToUserInput,
3098 - stopSession,
3099 - listSessions,
3100 - hasSession,
3101 - stopAll,
3102 - streamEvents: Stream.fromQueue(runtimeEventQueue),
3103 - } satisfies ClaudeAdapterShape;
3104 - });
3105 -}
3017 + yield* Effect.addFinalizer(() =>
3018 + Effect.forEach(
3019 + sessions,
3020 + ([, context]) =>
3021 + stopSessionInternal(context, {
3022 + emitExitEvent: false,
3023 + }),
3024 + { discard: true },
3025 + ).pipe(Effect.tap(() => Queue.shutdown(runtimeEventQueue))),
3026 + );
3027 +
3028 + return {
3029 + provider: PROVIDER,
3030 + capabilities: {
3031 + sessionModelSwitch: "in-session",
3032 + },
3033 + startSession,
3034 + sendTurn,
3035 + interruptTurn,
3036 + readThread,
3037 + rollbackThread,
3038 + respondToRequest,
3039 + respondToUserInput,
3040 + stopSession,
3041 + listSessions,
3042 + hasSession,
3043 + stopAll,
3044 + streamEvents: Stream.fromQueue(runtimeEventQueue),
3045 + } satisfies ClaudeAdapterShape;
3046 +});
3047
3048 export const ClaudeAdapterLive = Layer.effect(ClaudeAdapter, makeClaudeAdapter());
3049
docs/effect-fn-checklist.md new
+183
@@ -0,0 +1,183 @@
1 +# Effect.fn Refactor Checklist
2 +
3 +Generated from a repo scan for non-test wrapper-style candidates matching either `=> Effect.gen(function* ...)` or `return Effect.gen(function* ...)`.
4 +
5 +Refactor Method:
6 +
7 +```ts
8 +// Old
9 +function old () {
10 + return Effect.gen(function* () {
11 + ...
12 + });
13 +}
14 +
15 +const old2 = () => Effect.gen(function* () {
16 + ...
17 +});
18 +```
19 +
20 +```ts
21 +// New
22 +const new = Effect.fn('functionName')(function* () {
23 + ...
24 +})
25 +```
26 +
27 +## Summary
28 +
29 +- Total non-test candidates: `322`
30 +
31 +## Suggested Order
32 +
33 +- [ ] `apps/server/src/provider/Layers/ProviderService.ts`
34 +- [x] `apps/server/src/provider/Layers/ClaudeAdapter.ts`
35 +- [ ] `apps/server/src/provider/Layers/CodexAdapter.ts`
36 +- [ ] `apps/server/src/git/Layers/GitCore.ts`
37 +- [ ] `apps/server/src/git/Layers/GitManager.ts`
38 +- [ ] `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
39 +- [ ] `apps/server/src/orchestration/Layers/ProjectionPipeline.ts`
40 +- [ ] `apps/server/src/orchestration/Layers/OrchestrationEngine.ts`
41 +- [ ] `apps/server/src/provider/Layers/EventNdjsonLogger.ts`
42 +- [ ] `Everything else`
43 +
44 +## Checklist
45 +
46 +### `apps/server/src/provider/Layers/ClaudeAdapter.ts` (`62`)
47 +
48 +- [x] [buildUserMessageEffect](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L554)
49 +- [x] [makeClaudeAdapter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L913)
50 +- [x] [startSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2414)
51 +- [x] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2887)
52 +- [x] [interruptTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2975)
53 +- [x] [readThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2984)
54 +- [x] [rollbackThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L2990)
55 +- [x] [stopSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeAdapter.ts#L3039)
56 +- [x] Internal helpers and callback wrappers in this file
57 +
58 +### `apps/server/src/git/Layers/GitCore.ts` (`58`)
59 +
60 +- [ ] [makeGitCore](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L495)
61 +- [ ] [handleTraceLine](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L317)
62 +- [ ] [emitCompleteLines](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L449)
63 +- [ ] [commit](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1178)
64 +- [ ] [pushCurrentBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1217)
65 +- [ ] [pullCurrentBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1316)
66 +- [ ] [checkoutBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1697)
67 +- [ ] Service methods and callback wrappers in this file
68 +
69 +### `apps/server/src/git/Layers/GitManager.ts` (`28`)
70 +
71 +- [ ] [configurePullRequestHeadUpstream](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L387)
72 +- [ ] [materializePullRequestHeadBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L428)
73 +- [ ] [findOpenPr](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L576)
74 +- [ ] [findLatestPr](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L602)
75 +- [ ] [runCommitStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L728)
76 +- [ ] [runPrStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L842)
77 +- [ ] [runFeatureBranchStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L1106)
78 +- [ ] Remaining helpers and nested callback wrappers in this file
79 +
80 +### `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` (`25`)
81 +
82 +- [ ] [runProjectorForEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L1161)
83 +- [ ] [applyProjectsProjection](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L357)
84 +- [ ] [applyThreadsProjection](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L415)
85 +- [ ] `Effect.forEach(..., threadId => Effect.gen(...))` callbacks around `L250`
86 +- [ ] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L264`
87 +- [ ] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L305`
88 +- [ ] Remaining apply helpers in this file
89 +
90 +### `apps/server/src/provider/Layers/ProviderService.ts` (`24`)
91 +
92 +- [ ] [makeProviderService](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L134)
93 +- [ ] [recoverSessionForThread](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L196)
94 +- [ ] [resolveRoutableSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L255)
95 +- [ ] [startSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L284)
96 +- [ ] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L347)
97 +- [ ] [interruptTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L393)
98 +- [ ] [respondToRequest](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L411)
99 +- [ ] [respondToUserInput](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L430)
100 +- [ ] [stopSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L445)
101 +- [ ] [listSessions](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L466)
102 +- [ ] [rollbackConversation](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L516)
103 +- [ ] [runStopAll](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderService.ts#L538)
104 +
105 +### `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (`14`)
106 +
107 +- [ ] [finalizeAssistantMessage](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L680)
108 +- [ ] [upsertProposedPlan](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L722)
109 +- [ ] [finalizeBufferedProposedPlan](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L761)
110 +- [ ] [clearTurnStateForSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L800)
111 +- [ ] [processRuntimeEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L908)
112 +- [ ] Nested callback wrappers in this file
113 +
114 +### `apps/server/src/provider/Layers/CodexAdapter.ts` (`12`)
115 +
116 +- [ ] [makeCodexAdapter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1317)
117 +- [ ] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1399)
118 +- [ ] [writeNativeEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1546)
119 +- [ ] [listener](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1555)
120 +- [ ] Remaining nested callback wrappers in this file
121 +
122 +### `apps/server/src/checkpointing/Layers/CheckpointStore.ts` (`10`)
123 +
124 +- [ ] [captureCheckpoint](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointStore.ts#L89)
125 +- [ ] [restoreCheckpoint](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointStore.ts#L183)
126 +- [ ] [diffCheckpoints](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointStore.ts#L220)
127 +- [ ] [deleteCheckpointRefs](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointStore.ts#L252)
128 +- [ ] Nested callback wrappers in this file
129 +
130 +### `apps/server/src/provider/Layers/EventNdjsonLogger.ts` (`9`)
131 +
132 +- [ ] [toLogMessage](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L77)
133 +- [ ] [makeThreadWriter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L102)
134 +- [ ] [makeEventNdjsonLogger](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L174)
135 +- [ ] [write](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L231)
136 +- [ ] [close](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/EventNdjsonLogger.ts#L247)
137 +- [ ] Flush and writer-resolution callback wrappers in this file
138 +
139 +### `apps/server/scripts/cli.ts` (`8`)
140 +
141 +- [ ] Command handlers around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L125)
142 +- [ ] Command handlers around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L170)
143 +- [ ] Resource callbacks around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L221)
144 +- [ ] Resource callbacks around [cli.ts](/Users/julius/Development/Work/codething-mvp/apps/server/scripts/cli.ts#L239)
145 +
146 +### `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` (`7`)
147 +
148 +- [ ] [processEnvelope](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L64)
149 +- [ ] [dispatch](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L218)
150 +- [ ] Catch/stream callback wrappers around [OrchestrationEngine.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L162)
151 +- [ ] Catch/stream callback wrappers around [OrchestrationEngine.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/OrchestrationEngine.ts#L200)
152 +
153 +### `apps/server/src/orchestration/projector.ts` (`5`)
154 +
155 +- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L242)
156 +- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L336)
157 +- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L397)
158 +- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L446)
159 +- [ ] `switch` branch wrapper at [projector.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/projector.ts#L478)
160 +
161 +### Smaller clusters
162 +
163 +- [ ] [packages/shared/src/DrainableWorker.ts](/Users/julius/Development/Work/codething-mvp/packages/shared/src/DrainableWorker.ts) (`4`)
164 +- [ ] [apps/server/src/wsServer/pushBus.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/wsServer/pushBus.ts) (`4`)
165 +- [ ] [apps/server/src/wsServer.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/wsServer.ts) (`4`)
166 +- [ ] [apps/server/src/provider/Layers/ProviderRegistry.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderRegistry.ts) (`4`)
167 +- [ ] [apps/server/src/persistence/Layers/Sqlite.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/Layers/Sqlite.ts) (`4`)
168 +- [ ] [apps/server/src/orchestration/Layers/ProviderCommandReactor.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts) (`4`)
169 +- [ ] [apps/server/src/main.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/main.ts) (`4`)
170 +- [ ] [apps/server/src/keybindings.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/keybindings.ts) (`4`)
171 +- [ ] [apps/server/src/git/Layers/CodexTextGeneration.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/CodexTextGeneration.ts) (`4`)
172 +- [ ] [apps/server/src/serverLayers.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/serverLayers.ts) (`3`)
173 +- [ ] [apps/server/src/telemetry/Layers/AnalyticsService.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/telemetry/Layers/AnalyticsService.ts) (`2`)
174 +- [ ] [apps/server/src/telemetry/Identify.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/telemetry/Identify.ts) (`2`)
175 +- [ ] [apps/server/src/provider/Layers/ProviderAdapterRegistry.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ProviderAdapterRegistry.ts) (`2`)
176 +- [ ] [apps/server/src/provider/Layers/CodexProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexProvider.ts) (`2`)
177 +- [ ] [apps/server/src/provider/Layers/ClaudeProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/ClaudeProvider.ts) (`2`)
178 +- [ ] [apps/server/src/persistence/NodeSqliteClient.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/NodeSqliteClient.ts) (`2`)
179 +- [ ] [apps/server/src/persistence/Migrations.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/persistence/Migrations.ts) (`2`)
180 +- [ ] [apps/server/src/open.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/open.ts) (`2`)
181 +- [ ] [apps/server/src/git/Layers/ClaudeTextGeneration.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/ClaudeTextGeneration.ts) (`2`)
182 +- [ ] [apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts) (`2`)
183 +- [ ] [apps/server/src/provider/makeManagedServerProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/makeManagedServerProvider.ts) (`1`)