-
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathClaudeAdapter.ts
More file actions
3190 lines (2919 loc) · 104 KB
/
ClaudeAdapter.ts
File metadata and controls
3190 lines (2919 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ClaudeAdapterLive - Scoped live implementation for the Claude Agent provider adapter.
*
* Wraps `@anthropic-ai/claude-agent-sdk` query sessions behind the generic
* provider adapter contract and emits canonical runtime events.
*
* @module ClaudeAdapterLive
*/
import {
type CanUseTool,
query,
type Options as ClaudeQueryOptions,
type PermissionMode,
type PermissionResult,
type PermissionUpdate,
type SDKMessage,
type SDKResultMessage,
type SettingSource,
type SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import type { ContentBlockParam, MessageParam } from "@anthropic-ai/sdk/resources";
import {
ApprovalRequestId,
type CanonicalItemType,
type CanonicalRequestType,
EventId,
type ProviderApprovalDecision,
ProviderItemId,
type ProviderRuntimeEvent,
type ProviderRuntimeTurnStatus,
type ProviderSendTurnInput,
type ProviderSession,
type ThreadTokenUsageSnapshot,
type ProviderUserInputAnswers,
type RuntimeContentStreamKind,
RuntimeItemId,
RuntimeRequestId,
RuntimeTaskId,
ThreadId,
TurnId,
type UserInputQuestion,
} from "@okcode/contracts";
import {
applyClaudePromptEffortPrefix,
getReasoningEffortOptions,
resolveClaudeUltrathinkSdkConfig,
resolveReasoningEffortForProvider,
supportsClaudeFastMode,
supportsClaudeThinkingToggle,
supportsClaudeUltrathinkKeyword,
} from "@okcode/shared/model";
import {
compactNodeProcessEnv,
mergeNodeProcessEnv,
sanitizeShellEnvironment,
} from "@okcode/shared/environment";
import {
Cause,
DateTime,
Deferred,
Effect,
Exit,
FileSystem,
Fiber,
Layer,
Queue,
Random,
Ref,
Stream,
} from "effect";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import {
buildFileAttachmentContextText,
extractTextAttachmentContents,
} from "../../attachmentText.ts";
import { ServerConfig } from "../../config.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
ProviderAdapterSessionClosedError,
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../Errors.ts";
import { ClaudeAdapter, type ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "claudeAgent" as const;
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
type ClaudeToolResultStreamKind = Extract<
RuntimeContentStreamKind,
"command_output" | "file_change_output"
>;
type PromptQueueItem =
| {
readonly type: "message";
readonly message: SDKUserMessage;
}
| {
readonly type: "terminate";
};
interface ClaudeResumeState {
readonly threadId?: ThreadId;
readonly resume?: string;
readonly resumeSessionAt?: string;
readonly turnCount?: number;
}
interface ClaudeTurnState {
readonly turnId: TurnId;
readonly startedAt: string;
readonly items: Array<unknown>;
readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;
readonly assistantTextBlockOrder: Array<AssistantTextBlockState>;
readonly capturedProposedPlanKeys: Set<string>;
nextSyntheticAssistantBlockIndex: number;
}
interface AssistantTextBlockState {
readonly itemId: string;
readonly blockIndex: number;
emittedTextDelta: boolean;
fallbackText: string;
streamClosed: boolean;
completionEmitted: boolean;
}
interface PendingApproval {
readonly requestType: CanonicalRequestType;
readonly detail?: string;
readonly suggestions?: ReadonlyArray<PermissionUpdate>;
readonly decision: Deferred.Deferred<ProviderApprovalDecision>;
}
interface PendingUserInput {
readonly questions: ReadonlyArray<UserInputQuestion>;
readonly answers: Deferred.Deferred<ProviderUserInputAnswers>;
}
interface ToolInFlight {
readonly itemId: string;
readonly itemType: CanonicalItemType;
readonly toolName: string;
readonly title: string;
readonly detail?: string;
readonly input: Record<string, unknown>;
readonly partialInputJson: string;
readonly lastEmittedInputFingerprint?: string;
}
interface ClaudeSessionContext {
session: ProviderSession;
readonly promptQueue: Queue.Queue<PromptQueueItem>;
readonly query: ClaudeQueryRuntime;
streamFiber: Fiber.Fiber<void, Error> | undefined;
readonly startedAt: string;
readonly basePermissionMode: PermissionMode;
resumeSessionId: string | undefined;
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
readonly turns: Array<{
id: TurnId;
items: Array<unknown>;
}>;
readonly inFlightTools: Map<number, ToolInFlight>;
turnState: ClaudeTurnState | undefined;
lastKnownContextWindow: number | undefined;
lastAssistantUuid: string | undefined;
lastThreadStartedId: string | undefined;
stopped: boolean;
}
interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
readonly interrupt: () => Promise<void>;
readonly setModel: (model?: string) => Promise<void>;
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
readonly close: () => void;
}
export interface ClaudeAdapterLiveOptions {
readonly createQuery?: (input: {
readonly prompt: AsyncIterable<SDKUserMessage>;
readonly options: ClaudeQueryOptions;
}) => ClaudeQueryRuntime;
readonly nativeEventLogPath?: string;
readonly nativeEventLogger?: EventNdjsonLogger;
}
function isUuid(value: string): boolean {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
}
function isSyntheticClaudeThreadId(value: string): boolean {
return value.startsWith("claude-thread-");
}
function toMessage(cause: unknown, fallback: string): string {
if (cause instanceof Error && cause.message.length > 0) {
return cause.message;
}
return fallback;
}
function toError(cause: unknown, fallback: string): Error {
return cause instanceof Error ? cause : new Error(toMessage(cause, fallback));
}
function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray<string> {
const errors = Cause.prettyErrors(cause)
.map((error) => error.message.trim())
.filter((message) => message.length > 0);
if (errors.length > 0) {
return errors;
}
const squashed = toMessage(Cause.squash(cause), "").trim();
return squashed.length > 0 ? [squashed] : [];
}
function isClaudeInterruptedMessage(message: string): boolean {
const normalized = message.toLowerCase();
return (
normalized.includes("all fibers interrupted without error") ||
normalized.includes("request was aborted") ||
normalized.includes("interrupted by user")
);
}
function isClaudeInterruptedCause(cause: Cause.Cause<Error>): boolean {
return (
Cause.hasInterruptsOnly(cause) ||
normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage)
);
}
const CLAUDE_AUTH_ERROR_PATTERNS = [
"oauth authentication is currently not supported",
"could not resolve authentication method",
"expected either apiKey or authToken to be set",
"no access token was provided",
"no auth token was provided",
] as const;
function isClaudeAuthErrorMessage(message: string): boolean {
const normalized = message.toLowerCase();
return CLAUDE_AUTH_ERROR_PATTERNS.some((pattern) => normalized.includes(pattern.toLowerCase()));
}
function isClaudeAuthCause(cause: Cause.Cause<Error>): boolean {
return normalizeClaudeStreamMessages(cause).some(isClaudeAuthErrorMessage);
}
function claudeAuthFailureMessage(): string {
return "Claude Code must be authenticated with `claude auth login` before starting a session. API key and auth token credentials are not supported.";
}
function messageFromClaudeStreamCause(cause: Cause.Cause<Error>, fallback: string): string {
return normalizeClaudeStreamMessages(cause)[0] ?? fallback;
}
function interruptionMessageFromClaudeCause(cause: Cause.Cause<Error>): string {
const message = messageFromClaudeStreamCause(cause, "Claude runtime interrupted.");
return isClaudeInterruptedMessage(message) ? "Claude runtime interrupted." : message;
}
function resultErrorsText(result: SDKResultMessage): string {
return "errors" in result && Array.isArray(result.errors)
? result.errors.join(" ").toLowerCase()
: "";
}
function isInterruptedResult(result: SDKResultMessage): boolean {
const errors = resultErrorsText(result);
if (errors.includes("interrupt")) {
return true;
}
return (
result.subtype === "error_during_execution" &&
result.is_error === false &&
(errors.includes("request was aborted") ||
errors.includes("interrupted by user") ||
errors.includes("aborted"))
);
}
function asRuntimeItemId(value: string): RuntimeItemId {
return RuntimeItemId.makeUnsafe(value);
}
function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | undefined {
if (!modelUsage || typeof modelUsage !== "object") {
return undefined;
}
let maxContextWindow: number | undefined;
for (const value of Object.values(modelUsage as Record<string, unknown>)) {
if (!value || typeof value !== "object") {
continue;
}
const contextWindow = (value as { contextWindow?: unknown }).contextWindow;
if (
typeof contextWindow !== "number" ||
!Number.isFinite(contextWindow) ||
contextWindow <= 0
) {
continue;
}
maxContextWindow = Math.max(maxContextWindow ?? 0, contextWindow);
}
return maxContextWindow;
}
function normalizeClaudeTokenUsage(
usage: unknown,
contextWindow?: number,
): ThreadTokenUsageSnapshot | undefined {
if (!usage || typeof usage !== "object") {
return undefined;
}
const record = usage as Record<string, unknown>;
const directUsedTokens =
typeof record.total_tokens === "number" && Number.isFinite(record.total_tokens)
? record.total_tokens
: undefined;
const inputTokens =
(typeof record.input_tokens === "number" && Number.isFinite(record.input_tokens)
? record.input_tokens
: 0) +
(typeof record.cache_creation_input_tokens === "number" &&
Number.isFinite(record.cache_creation_input_tokens)
? record.cache_creation_input_tokens
: 0) +
(typeof record.cache_read_input_tokens === "number" &&
Number.isFinite(record.cache_read_input_tokens)
? record.cache_read_input_tokens
: 0);
const outputTokens =
typeof record.output_tokens === "number" && Number.isFinite(record.output_tokens)
? record.output_tokens
: 0;
const derivedUsedTokens = inputTokens + outputTokens;
const usedTokens = directUsedTokens ?? (derivedUsedTokens > 0 ? derivedUsedTokens : undefined);
if (usedTokens === undefined || usedTokens <= 0) {
return undefined;
}
return {
usedTokens,
lastUsedTokens: usedTokens,
...(inputTokens > 0 ? { inputTokens } : {}),
...(outputTokens > 0 ? { outputTokens } : {}),
...(typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
? { maxTokens: contextWindow }
: {}),
...(typeof record.tool_uses === "number" && Number.isFinite(record.tool_uses)
? { toolUses: record.tool_uses }
: {}),
...(typeof record.duration_ms === "number" && Number.isFinite(record.duration_ms)
? { durationMs: record.duration_ms }
: {}),
};
}
function asCanonicalTurnId(value: TurnId): TurnId {
return value;
}
function asRuntimeRequestId(value: ApprovalRequestId): RuntimeRequestId {
return RuntimeRequestId.makeUnsafe(value);
}
function toPermissionMode(value: unknown): PermissionMode | undefined {
switch (value) {
case "default":
case "acceptEdits":
case "bypassPermissions":
case "plan":
case "dontAsk":
return value;
default:
return undefined;
}
}
function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undefined {
if (!resumeCursor || typeof resumeCursor !== "object") {
return undefined;
}
const cursor = resumeCursor as {
threadId?: unknown;
resume?: unknown;
sessionId?: unknown;
resumeSessionAt?: unknown;
turnCount?: unknown;
};
const threadIdCandidate = typeof cursor.threadId === "string" ? cursor.threadId : undefined;
const threadId =
threadIdCandidate && !isSyntheticClaudeThreadId(threadIdCandidate)
? ThreadId.makeUnsafe(threadIdCandidate)
: undefined;
const resumeCandidate =
typeof cursor.resume === "string"
? cursor.resume
: typeof cursor.sessionId === "string"
? cursor.sessionId
: undefined;
const resume = resumeCandidate && isUuid(resumeCandidate) ? resumeCandidate : undefined;
const resumeSessionAt =
typeof cursor.resumeSessionAt === "string" ? cursor.resumeSessionAt : undefined;
const turnCountValue = typeof cursor.turnCount === "number" ? cursor.turnCount : undefined;
return {
...(threadId ? { threadId } : {}),
...(resume ? { resume } : {}),
...(resumeSessionAt ? { resumeSessionAt } : {}),
...(turnCountValue !== undefined && Number.isInteger(turnCountValue) && turnCountValue >= 0
? { turnCount: turnCountValue }
: {}),
};
}
function classifyToolItemType(toolName: string): CanonicalItemType {
const normalized = toolName.toLowerCase();
if (normalized.includes("agent")) {
return "collab_agent_tool_call";
}
if (
normalized === "task" ||
normalized === "agent" ||
normalized.includes("subagent") ||
normalized.includes("sub-agent")
) {
return "collab_agent_tool_call";
}
if (
normalized.includes("bash") ||
normalized.includes("command") ||
normalized.includes("shell") ||
normalized.includes("terminal")
) {
return "command_execution";
}
if (
normalized.includes("edit") ||
normalized.includes("write") ||
normalized.includes("file") ||
normalized.includes("patch") ||
normalized.includes("replace") ||
normalized.includes("create") ||
normalized.includes("delete")
) {
return "file_change";
}
if (normalized.includes("mcp")) {
return "mcp_tool_call";
}
if (normalized.includes("websearch") || normalized.includes("web search")) {
return "web_search";
}
if (normalized.includes("image")) {
return "image_view";
}
return "dynamic_tool_call";
}
function isReadOnlyToolName(toolName: string): boolean {
const normalized = toolName.toLowerCase();
return (
normalized === "read" ||
normalized.includes("read file") ||
normalized.includes("view") ||
normalized.includes("grep") ||
normalized.includes("glob") ||
normalized.includes("search")
);
}
function classifyRequestType(toolName: string): CanonicalRequestType {
if (isReadOnlyToolName(toolName)) {
return "file_read_approval";
}
const itemType = classifyToolItemType(toolName);
return itemType === "command_execution"
? "command_execution_approval"
: itemType === "file_change"
? "file_change_approval"
: "dynamic_tool_call";
}
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
const commandValue = input.command ?? input.cmd;
const command = typeof commandValue === "string" ? commandValue : undefined;
if (command && command.trim().length > 0) {
return `${toolName}: ${command.trim().slice(0, 400)}`;
}
const serialized = JSON.stringify(input);
if (serialized.length <= 400) {
return `${toolName}: ${serialized}`;
}
return `${toolName}: ${serialized.slice(0, 397)}...`;
}
function titleForTool(itemType: CanonicalItemType): string {
switch (itemType) {
case "command_execution":
return "Command run";
case "file_change":
return "File change";
case "mcp_tool_call":
return "MCP tool call";
case "collab_agent_tool_call":
return "Subagent task";
case "web_search":
return "Web search";
case "image_view":
return "Image view";
case "dynamic_tool_call":
return "Tool call";
default:
return "Item";
}
}
const SUPPORTED_CLAUDE_IMAGE_MIME_TYPES = new Set([
"image/gif",
"image/jpeg",
"image/png",
"image/webp",
]);
type ClaudeImageMimeType = "image/gif" | "image/jpeg" | "image/png" | "image/webp";
function isClaudeImageMimeType(value: string): value is ClaudeImageMimeType {
return SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(value as ClaudeImageMimeType);
}
const CLAUDE_SETTING_SOURCES = [
"user",
"project",
"local",
] as const satisfies ReadonlyArray<SettingSource>;
function buildPromptText(input: ProviderSendTurnInput): string {
const requestedEffort = resolveReasoningEffortForProvider(
"claudeAgent",
input.modelOptions?.claudeAgent?.effort ?? null,
);
const supportedEffortOptions = getReasoningEffortOptions("claudeAgent", input.model);
const promptEffort =
requestedEffort === "ultrathink" && supportsClaudeUltrathinkKeyword(input.model)
? "ultrathink"
: requestedEffort && supportedEffortOptions.includes(requestedEffort)
? requestedEffort
: null;
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
}
function buildUserMessage(input: {
readonly sdkContent: Array<ContentBlockParam>;
}): SDKUserMessage {
const message: MessageParam = {
role: "user",
content: input.sdkContent,
};
return {
type: "user",
session_id: "",
parent_tool_use_id: null,
message,
};
}
function buildClaudeImageContentBlock(input: {
readonly mimeType: ClaudeImageMimeType;
readonly bytes: Uint8Array;
}): ContentBlockParam {
return {
type: "image",
source: {
type: "base64",
media_type: input.mimeType,
data: Buffer.from(input.bytes).toString("base64"),
},
};
}
function buildUserMessageEffect(
input: ProviderSendTurnInput,
dependencies: {
readonly fileSystem: FileSystem.FileSystem;
readonly attachmentsDir: string;
},
): Effect.Effect<SDKUserMessage, ProviderAdapterRequestError> {
return Effect.gen(function* () {
const imageAttachments: Array<
Extract<NonNullable<ProviderSendTurnInput["attachments"]>[number], { type: "image" }>
> = [];
const fileAttachments: Array<{
readonly attachment: Extract<
NonNullable<ProviderSendTurnInput["attachments"]>[number],
{ type: "file" }
>;
readonly text: string;
}> = [];
for (const attachment of input.attachments ?? []) {
if (attachment.type === "image") {
imageAttachments.push(attachment);
continue;
}
const attachmentPath = resolveAttachmentPath({
attachmentsDir: dependencies.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: toMessage(cause, "Failed to read attachment file."),
cause,
}),
),
);
const text = extractTextAttachmentContents({
mimeType: attachment.mimeType,
fileName: attachment.name,
bytes,
});
if (text === null) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: `Unsupported file attachment '${attachment.name}'. Attach UTF-8 text files or images.`,
});
}
fileAttachments.push({ attachment, text });
}
const text = buildFileAttachmentContextText({
baseText: buildPromptText(input),
attachments: fileAttachments,
});
const sdkContent: Array<ContentBlockParam> = [];
if (text.length > 0) {
sdkContent.push({ type: "text", text });
}
for (const attachment of imageAttachments) {
if (!isClaudeImageMimeType(attachment.mimeType)) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`,
});
}
const attachmentPath = resolveAttachmentPath({
attachmentsDir: dependencies.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: toMessage(cause, "Failed to read attachment file."),
cause,
}),
),
);
sdkContent.push(
buildClaudeImageContentBlock({
mimeType: attachment.mimeType,
bytes,
}),
);
}
return buildUserMessage({ sdkContent });
});
}
function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStatus {
if (result.subtype === "success") {
return "completed";
}
const errors = resultErrorsText(result);
if (isInterruptedResult(result)) {
return "interrupted";
}
if (errors.includes("cancel")) {
return "cancelled";
}
return "failed";
}
function streamKindFromDeltaType(deltaType: string): ClaudeTextStreamKind {
return deltaType.includes("thinking") ? "reasoning_text" : "assistant_text";
}
function nativeProviderRefs(
_context: ClaudeSessionContext,
options?: {
readonly providerItemId?: string | undefined;
},
): NonNullable<ProviderRuntimeEvent["providerRefs"]> {
if (options?.providerItemId) {
return {
providerItemId: ProviderItemId.makeUnsafe(options.providerItemId),
};
}
return {};
}
function extractAssistantTextBlocks(message: SDKMessage): Array<string> {
if (message.type !== "assistant") {
return [];
}
const content = (message.message as { content?: unknown } | undefined)?.content;
if (!Array.isArray(content)) {
return [];
}
const fragments: string[] = [];
for (const block of content) {
if (!block || typeof block !== "object") {
continue;
}
const candidate = block as { type?: unknown; text?: unknown };
if (
candidate.type === "text" &&
typeof candidate.text === "string" &&
candidate.text.length > 0
) {
fragments.push(candidate.text);
}
}
return fragments;
}
function extractContentBlockText(block: unknown): string {
if (!block || typeof block !== "object") {
return "";
}
const candidate = block as { type?: unknown; text?: unknown };
return candidate.type === "text" && typeof candidate.text === "string" ? candidate.text : "";
}
function extractTextContent(value: unknown): string {
if (typeof value === "string") {
return value;
}
if (Array.isArray(value)) {
return value.map((entry) => extractTextContent(entry)).join("");
}
if (!value || typeof value !== "object") {
return "";
}
const record = value as {
text?: unknown;
content?: unknown;
};
if (typeof record.text === "string") {
return record.text;
}
return extractTextContent(record.content);
}
function extractExitPlanModePlan(value: unknown): string | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const record = value as {
plan?: unknown;
};
return typeof record.plan === "string" && record.plan.trim().length > 0
? record.plan.trim()
: undefined;
}
function exitPlanCaptureKey(input: {
readonly toolUseId?: string | undefined;
readonly planMarkdown: string;
}): string {
return input.toolUseId && input.toolUseId.length > 0
? `tool:${input.toolUseId}`
: `plan:${input.planMarkdown}`;
}
function tryParseJsonRecord(value: string): Record<string, unknown> | undefined {
try {
const parsed = JSON.parse(value);
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined;
} catch {
return undefined;
}
}
function toolInputFingerprint(input: Record<string, unknown>): string | undefined {
try {
return JSON.stringify(input);
} catch {
return undefined;
}
}
function toolResultStreamKind(itemType: CanonicalItemType): ClaudeToolResultStreamKind | undefined {
switch (itemType) {
case "command_execution":
return "command_output";
case "file_change":
return "file_change_output";
default:
return undefined;
}
}
function toolResultBlocksFromUserMessage(message: SDKMessage): Array<{
readonly toolUseId: string;
readonly block: Record<string, unknown>;
readonly text: string;
readonly isError: boolean;
}> {
if (message.type !== "user") {
return [];
}
const content = (message.message as { content?: unknown } | undefined)?.content;
if (!Array.isArray(content)) {
return [];
}
const blocks: Array<{
readonly toolUseId: string;
readonly block: Record<string, unknown>;
readonly text: string;
readonly isError: boolean;
}> = [];
for (const entry of content) {
if (!entry || typeof entry !== "object") {
continue;
}
const block = entry as Record<string, unknown>;
if (block.type !== "tool_result") {
continue;
}
const toolUseId = typeof block.tool_use_id === "string" ? block.tool_use_id : undefined;
if (!toolUseId) {
continue;
}
blocks.push({
toolUseId,
block,
text: extractTextContent(block.content),
isError: block.is_error === true,
});
}
return blocks;
}
function toSessionError(
threadId: ThreadId,
cause: unknown,
): ProviderAdapterSessionNotFoundError | ProviderAdapterSessionClosedError | undefined {
const normalized = toMessage(cause, "").toLowerCase();
if (normalized.includes("unknown session") || normalized.includes("not found")) {
return new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
threadId,
cause,
});
}
if (normalized.includes("closed")) {
return new ProviderAdapterSessionClosedError({
provider: PROVIDER,
threadId,
cause,
});
}
return undefined;
}
function toRequestError(threadId: ThreadId, method: string, cause: unknown): ProviderAdapterError {
const sessionError = toSessionError(threadId, cause);
if (sessionError) {
return sessionError;
}
return new ProviderAdapterRequestError({
provider: PROVIDER,
method,
detail: toMessage(cause, `${method} failed`),
cause,
});
}
function sdkMessageType(value: unknown): string | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const record = value as { type?: unknown };
return typeof record.type === "string" ? record.type : undefined;
}
function sdkMessageSubtype(value: unknown): string | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
const record = value as { subtype?: unknown };
return typeof record.subtype === "string" ? record.subtype : undefined;
}
function sdkNativeMethod(message: SDKMessage): string {
const subtype = sdkMessageSubtype(message);
if (subtype) {
return `claude/${message.type}/${subtype}`;
}
if (message.type === "stream_event") {
const streamType = sdkMessageType(message.event);
if (streamType) {
const deltaType =
streamType === "content_block_delta"
? sdkMessageType((message.event as { delta?: unknown }).delta)
: undefined;
if (deltaType) {
return `claude/${message.type}/${streamType}/${deltaType}`;
}
return `claude/${message.type}/${streamType}`;
}
}
return `claude/${message.type}`;
}
function sdkNativeItemId(message: SDKMessage): string | undefined {
if (message.type === "assistant") {
const maybeId = (message.message as { id?: unknown }).id;
if (typeof maybeId === "string") {
return maybeId;
}
return undefined;
}
if (message.type === "user") {
return toolResultBlocksFromUserMessage(message)[0]?.toolUseId;
}
if (message.type === "stream_event") {
const event = message.event as {
type?: unknown;
content_block?: { id?: unknown };
};