@@ -1,698 +0,0 @@
1-import Anthropic from "@anthropic-ai/sdk";
2-import type {
3- ContentBlockParam,
4- MessageCreateParamsStreaming,
5- MessageParam,
6-} from "@anthropic-ai/sdk/resources/messages.js";
7-import { zodSchema } from "ai";
8-
9-import { isApiLogEnabled, logApiEvent } from "./api-log.ts";
10-import { normalizeUnknownError } from "./error-utils.ts";
11-import type { ThinkingEffort } from "./provider-options.ts";
12-import type { CoreMessage } from "./turn.ts";
13-import {
14- type ContextPruningMode,
15- DEFAULT_TOOL_RESULT_PAYLOAD_CAP_BYTES,
16-} from "./turn-context.ts";
17-import { buildTurnPreparation } from "./turn-request.ts";
18-import type { ToolDef, TurnEvent } from "./types.ts";
19-
20-const MAX_STEPS = 50;
21-const MAX_OUTPUT_TOKENS = 16384;
22-const CC_VERSION = "2.1.75";
23-
24-// ─── Anthropic client management ──────────────────────────────────────────────
25-
26-let cachedClient: { token: string; client: Anthropic } | null = null;
27-
28-function getClient(token: string): Anthropic {
29- if (cachedClient?.token === token && cachedClient.client)
30- return cachedClient.client;
31- const client = new Anthropic({
32- apiKey: null,
33- authToken: token,
34- maxRetries: 5,
35- dangerouslyAllowBrowser: true,
36- defaultHeaders: {
37- accept: "application/json",
38- "anthropic-dangerous-direct-browser-access": "true",
39- "anthropic-beta": "claude-code-20250219,oauth-2025-04-20",
40- "user-agent": `claude-cli/${CC_VERSION}`,
41- "x-app": "cli",
42- },
43- });
44- cachedClient = { token, client };
45- return client;
46-}
47-
48-// ─── Thinking / effort helpers ────────────────────────────────────────────────
49-
50-function supportsAdaptiveThinking(modelId: string): boolean {
51- return modelId.includes("opus-4-6") || modelId.includes("sonnet-4-6");
52-}
53-
54-function mapEffort(
55- effort: ThinkingEffort | undefined,
56- modelId: string,
57-): string | undefined {
58- if (!effort) return undefined;
59- const map: Record<ThinkingEffort, string> = {
60- low: "low",
61- medium: "medium",
62- high: "high",
63- xhigh: modelId.includes("opus-4-6") ? "max" : "high",
64- };
65- return map[effort];
66-}
67-
68-// ─── Message conversion: CoreMessage[] → Anthropic MessageParam[] ─────────────
69-
70-// CoreMessage content parts are loosely typed (round-tripped from SQLite JSON)
71-// so we cast through a minimal record type to access provider-specific fields.
72-type Msg = { role: string; content: unknown };
73-type Part = Record<string, unknown>;
74-
75-function coreToAnthropicMessages(messages: CoreMessage[]): {
76- system: string | undefined;
77- params: MessageParam[];
78-} {
79- let systemPrompt: string | undefined;
80- const params: MessageParam[] = [];
81-
82- // First pass: collect all tool_use IDs so we can drop orphaned tool_results
83- // (context pruning may remove assistant messages with tool_use blocks while
84- // keeping the user messages with their tool_result blocks).
85- const toolUseIds = new Set<string>();
86- for (const msg of messages as unknown as Msg[]) {
87- if (msg.role !== "assistant" || !Array.isArray(msg.content)) continue;
88- for (const part of msg.content as Part[]) {
89- if (part.type === "tool-call" && part.toolCallId) {
90- toolUseIds.add(part.toolCallId as string);
91- }
92- }
93- }
94-
95- for (const msg of messages as unknown as Msg[]) {
96- if (msg.role === "system") {
97- systemPrompt =
98- typeof msg.content === "string"
99- ? msg.content
100- : Array.isArray(msg.content)
101- ? (msg.content as Part[])
102- .filter((p) => p.type === "text")
103- .map((p) => p.text as string)
104- .join("\n")
105- : undefined;
106- continue;
107- }
108-
109- if (msg.role === "user") {
110- if (typeof msg.content === "string") {
111- if (msg.content.trim())
112- params.push({ role: "user", content: msg.content });
113- continue;
114- }
115- if (Array.isArray(msg.content)) {
116- const blocks: ContentBlockParam[] = [];
117- for (const part of msg.content as Part[]) {
118- if (part.type === "text" && (part.text as string)?.trim()) {
119- blocks.push({ type: "text", text: part.text as string });
120- } else if (part.type === "tool-result") {
121- // Drop orphaned tool_results whose tool_use was pruned
122- if (!toolUseIds.has(part.toolCallId as string)) continue;
123- blocks.push({
124- type: "tool_result",
125- tool_use_id: part.toolCallId,
126- content:
127- typeof part.result === "string"
128- ? part.result
129- : JSON.stringify(part.result ?? part.output ?? ""),
130- is_error: part.isError ?? false,
131- } as ContentBlockParam);
132- } else if (part.type === "image") {
133- blocks.push({
134- type: "image",
135- source: {
136- type: "base64",
137- media_type: part.mimeType ?? "image/png",
138- data: part.data,
139- },
140- } as ContentBlockParam);
141- }
142- }
143- if (blocks.length > 0) params.push({ role: "user", content: blocks });
144- }
145- continue;
146- }
147-
148- if (msg.role === "assistant") {
149- if (typeof msg.content === "string") {
150- if (msg.content.trim())
151- params.push({ role: "assistant", content: msg.content });
152- continue;
153- }
154- if (Array.isArray(msg.content)) {
155- const blocks: ContentBlockParam[] = [];
156- for (const part of msg.content as Part[]) {
157- if (part.type === "text" && (part.text as string)?.trim()) {
158- blocks.push({ type: "text", text: part.text as string });
159- } else if (part.type === "tool-call") {
160- blocks.push({
161- type: "tool_use",
162- id: part.toolCallId,
163- name: part.toolName,
164- input: part.args ?? {},
165- } as ContentBlockParam);
166- } else if (part.type === "thinking") {
167- if (part.redacted && part.signature) {
168- blocks.push({
169- type: "redacted_thinking",
170- data: part.signature,
171- } as ContentBlockParam);
172- } else if (
173- (part.text as string)?.trim() &&
174- (part.signature as string)?.trim()
175- ) {
176- blocks.push({
177- type: "thinking",
178- thinking: part.text,
179- signature: part.signature,
180- } as ContentBlockParam);
181- }
182- }
183- }
184- if (blocks.length > 0)
185- params.push({ role: "assistant", content: blocks });
186- }
187- }
188- }
189-
190- return { system: systemPrompt, params };
191-}
192-
193-// ─── Tool conversion: ToolDef[] → Anthropic Tool[] ────────────────────────────
194-
195-function convertTools(tools: ToolDef[]): Anthropic.Messages.Tool[] {
196- return tools.map((tool) => {
197- const schema = zodSchema(tool.schema as Parameters<typeof zodSchema>[0])
198- .jsonSchema as {
199- properties?: Record<string, unknown>;
200- required?: string[];
201- };
202- return {
203- name: tool.name,
204- description: tool.description,
205- input_schema: {
206- type: "object" as const,
207- properties: schema.properties ?? {},
208- required: schema.required ?? [],
209- },
210- };
211- });
212-}
213-
214-// ─── Response conversion: Anthropic → CoreMessage[] ───────────────────────────
215-
216-interface ToolCallCollected {
217- id: string;
218- name: string;
219- args: unknown;
220-}
221-
222-interface ToolResultCollected {
223- toolCallId: string;
224- toolName: string;
225- result: unknown;
226- isError: boolean;
227-}
228-
229-function buildCoreMessages(
230- assistantText: string,
231- thinkingBlocks: Array<{
232- text: string;
233- signature: string;
234- redacted?: boolean;
235- }>,
236- toolCalls: ToolCallCollected[],
237- toolResults: ToolResultCollected[],
238-): CoreMessage[] {
239- const messages: CoreMessage[] = [];
240-
241- // Assistant message with text + thinking + tool calls
242- const parts: unknown[] = [];
243- for (const tb of thinkingBlocks) {
244- if (tb.redacted) {
245- parts.push({
246- type: "thinking",
247- text: "[Reasoning redacted]",
248- signature: tb.signature,
249- redacted: true,
250- });
251- } else {
252- parts.push({
253- type: "thinking",
254- text: tb.text,
255- signature: tb.signature,
256- });
257- }
258- }
259- if (assistantText.trim()) {
260- parts.push({ type: "text", text: assistantText });
261- }
262- for (const tc of toolCalls) {
263- parts.push({
264- type: "tool-call",
265- toolCallId: tc.id,
266- toolName: tc.name,
267- args: tc.args,
268- });
269- }
270- if (parts.length > 0) {
271- messages.push({
272- role: "assistant",
273- content: parts,
274- } as unknown as CoreMessage);
275- }
276-
277- // Tool results as user message
278- if (toolResults.length > 0) {
279- const resultParts = toolResults.map((tr) => ({
280- type: "tool-result" as const,
281- toolCallId: tr.toolCallId,
282- toolName: tr.toolName,
283- result: tr.result,
284- isError: tr.isError,
285- }));
286- messages.push({
287- role: "user",
288- content: resultParts,
289- } as unknown as CoreMessage);
290- }
291-
292- return messages;
293-}
294-
295-// ─── parseStreamingJson (for partial tool input) ──────────────────────────────
296-
297-function parseStreamingJson(partial: string): Record<string, unknown> {
298- try {
299- return JSON.parse(partial);
300- } catch {
301- try {
302- // Try closing open braces
303- let fixed = partial;
304- const opens = (fixed.match(/{/g) || []).length;
305- const closes = (fixed.match(/}/g) || []).length;
306- for (let i = 0; i < opens - closes; i++) fixed += "}";
307- return JSON.parse(fixed);
308- } catch {
309- return {};
310- }
311- }
312-}
313-
314-// ─── Main entry point ─────────────────────────────────────────────────────────
315-
316-export async function* runTurnAnthropicOAuth(options: {
317- token: string;
318- modelString: string;
319- messages: CoreMessage[];
320- tools: ToolDef[];
321- systemPrompt?: string;
322- signal?: AbortSignal;
323- thinkingEffort?: ThinkingEffort;
324- pruningMode?: ContextPruningMode;
325- toolResultPayloadCapBytes?: number;
326- promptCachingEnabled?: boolean;
327-}): AsyncGenerator<TurnEvent> {
328- const {
329- token,
330- modelString,
331- messages,
332- tools,
333- systemPrompt,
334- signal,
335- thinkingEffort,
336- pruningMode = "balanced",
337- promptCachingEnabled = true,
338- toolResultPayloadCapBytes = DEFAULT_TOOL_RESULT_PAYLOAD_CAP_BYTES,
339- } = options;
340-
341- const modelId = modelString.replace(/^anthropic\//, "");
342- const client = getClient(token);
343- const anthropicTools = convertTools(tools);
344- const toolExecutors = new Map(tools.map((t) => [t.name, t.execute]));
345-
346- // Track totals
347- let totalInputTokens = 0;
348- let totalOutputTokens = 0;
349- let contextTokens = 0;
350- let stepCount = 0;
351- const allNewMessages: CoreMessage[] = [];
352-
353- try {
354- // Prepare messages (pruning, compaction, cache breakpoints)
355- const { prepared } = buildTurnPreparation({
356- modelString,
357- messages,
358- thinkingEffort,
359- promptCachingEnabled,
360- openaiPromptCacheRetention: "in_memory",
361- googleCachedContent: null,
362- toolCount: tools.length,
363- systemPrompt,
364- pruningMode,
365- toolResultPayloadCapBytes,
366- });
367-
368- logApiEvent("turn start", {
369- modelString,
370- messageCount: messages.length,
371- reasoningSummaryRequested: false,
372- pruningMode,
373- toolResultPayloadCapBytes,
374- });
375-
376- if (prepared.pruned) {
377- yield {
378- type: "context-pruned",
379- mode: pruningMode as "balanced" | "aggressive",
380- beforeMessageCount: prepared.prePruneMessageCount,
381- afterMessageCount: prepared.postPruneMessageCount,
382- removedMessageCount:
383- prepared.prePruneMessageCount - prepared.postPruneMessageCount,
384- beforeTotalBytes: prepared.prePruneTotalBytes,
385- afterTotalBytes: prepared.postPruneTotalBytes,
386- removedBytes:
387- prepared.prePruneTotalBytes - prepared.postPruneTotalBytes,
388- };
389- }
390-
391- // Convert prepared messages to Anthropic format
392- const { system: extractedSystem, params: anthropicMessages } =
393- coreToAnthropicMessages(prepared.messages);
394-
395- // Build system prompt array — CC identity MUST be a separate first block
396- const ccPrefix =
397- "You are Claude Code, Anthropic's official CLI for Claude.";
398- const sysText = prepared.systemPrompt ?? extractedSystem;
399- const systemBlocks: Anthropic.Messages.TextBlockParam[] = [
400- {
401- type: "text",
402- text: ccPrefix,
403- cache_control: { type: "ephemeral" },
404- },
405- ];
406- if (sysText) {
407- // Strip the CC prefix if it was already prepended
408- const clean = sysText.startsWith(ccPrefix)
409- ? sysText.slice(ccPrefix.length).replace(/^\n/, "")
410- : sysText;
411- if (clean.trim()) {
412- systemBlocks.push({
413- type: "text",
414- text: clean,
415- cache_control: { type: "ephemeral" },
416- });
417- }
418- }
419-
420- // Multi-step loop
421- const currentMessages = [...anthropicMessages];
422-
423- while (stepCount < MAX_STEPS) {
424- stepCount++;
425- const isLastStep = stepCount >= MAX_STEPS;
426-
427- const params: MessageCreateParamsStreaming = {
428- model: modelId,
429- max_tokens: MAX_OUTPUT_TOKENS,
430- system: systemBlocks,
431- messages: currentMessages,
432- tools: isLastStep ? [] : anthropicTools,
433- stream: true,
434- };
435-
436- // Configure thinking
437- if (thinkingEffort && supportsAdaptiveThinking(modelId)) {
438- params.thinking = { type: "adaptive" };
439- const effort = mapEffort(thinkingEffort, modelId);
440- if (effort) {
441- (params as unknown as Record<string, unknown>).output_config = {
442- effort,
443- };
444- }
445- }
446-
447- // Manage cache_control: max 4 total (2 system + up to 2 in messages).
448- // Remove old cache_control from messages and add to the last user message.
449- for (const m of currentMessages) {
450- if (!Array.isArray(m.content)) continue;
451- for (const block of m.content) {
452- if (typeof block === "object" && block !== null) {
453- delete (block as unknown as Record<string, unknown>).cache_control;
454- }
455- }
456- }
457- // Add cache_control to last user message's last block
458- const lastMsg =
459- currentMessages.length > 0
460- ? currentMessages[currentMessages.length - 1]
461- : undefined;
462- if (
463- lastMsg &&
464- lastMsg.role === "user" &&
465- Array.isArray(lastMsg.content)
466- ) {
467- const lastBlock = lastMsg.content[lastMsg.content.length - 1];
468- if (lastBlock && typeof lastBlock === "object") {
469- (lastBlock as unknown as Record<string, unknown>).cache_control = {
470- type: "ephemeral",
471- };
472- }
473- }
474-
475- if (isApiLogEnabled()) {
476- logApiEvent("Provider Request", {
477- url: "https://api.anthropic.com/v1/messages",
478- method: "POST",
479- model: modelId,
480- messageCount: currentMessages.length,
481- toolCount: params.tools?.length ?? 0,
482- });
483- }
484-
485- // Use non-streaming create with retries, then convert to stream behavior.
486- // The SDK's .stream() method doesn't retry on 500, but .create() does
487- // when maxRetries is set.
488- const stream = client.messages.stream(params, { signal });
489- let assistantText = "";
490- const thinkingBlocks: Array<{
491- text: string;
492- signature: string;
493- redacted?: boolean;
494- }> = [];
495- const toolCalls: ToolCallCollected[] = [];
496- let partialJson = "";
497- let currentToolId = "";
498- let currentToolName = "";
499- let stepInputTokens = 0;
500- let stepOutputTokens = 0;
501- let stopReason: string | undefined;
502-
503- for await (const event of stream) {
504- if (event.type === "message_start") {
505- stepInputTokens = event.message.usage.input_tokens || 0;
506- stepOutputTokens = event.message.usage.output_tokens || 0;
507- } else if (event.type === "content_block_start") {
508- if (event.content_block.type === "text") {
509- // text block starting
510- } else if (event.content_block.type === "thinking") {
511- thinkingBlocks.push({
512- text: "",
513- signature: "",
514- });
515- } else if (event.content_block.type === "redacted_thinking") {
516- thinkingBlocks.push({
517- text: "[Reasoning redacted]",
518- signature: (event.content_block as { data: string }).data,
519- redacted: true,
520- });
521- } else if (event.content_block.type === "tool_use") {
522- currentToolId = event.content_block.id;
523- currentToolName = event.content_block.name;
524- partialJson = "";
525- }
526- } else if (event.type === "content_block_delta") {
527- if (event.delta.type === "text_delta") {
528- assistantText += event.delta.text;
529- yield { type: "text-delta", delta: event.delta.text };
530- } else if (event.delta.type === "thinking_delta") {
531- const tb = thinkingBlocks[thinkingBlocks.length - 1];
532- if (tb) tb.text += event.delta.thinking;
533- yield {
534- type: "reasoning-delta",
535- delta: event.delta.thinking,
536- };
537- } else if (event.delta.type === "input_json_delta") {
538- partialJson += event.delta.partial_json;
539- } else if (event.delta.type === "signature_delta") {
540- const tb = thinkingBlocks[thinkingBlocks.length - 1];
541- if (tb) tb.signature += event.delta.signature;
542- }
543- } else if (event.type === "content_block_stop") {
544- if (currentToolId && currentToolName) {
545- const args = parseStreamingJson(partialJson);
546- toolCalls.push({
547- id: currentToolId,
548- name: currentToolName,
549- args,
550- });
551- yield {
552- type: "tool-call-start",
553- toolCallId: currentToolId,
554- toolName: currentToolName,
555- args,
556- };
557- currentToolId = "";
558- currentToolName = "";
559- partialJson = "";
560- }
561- } else if (event.type === "message_delta") {
562- if (event.delta.stop_reason) {
563- stopReason = event.delta.stop_reason;
564- }
565- if (event.usage.output_tokens != null) {
566- stepOutputTokens = event.usage.output_tokens;
567- }
568- }
569- }
570-
571- totalInputTokens += stepInputTokens;
572- totalOutputTokens += stepOutputTokens;
573- contextTokens = stepInputTokens;
574-
575- logApiEvent("step finish", {
576- stepNumber: stepCount,
577- finishReason: stopReason,
578- usage: {
579- inputTokens: stepInputTokens,
580- outputTokens: stepOutputTokens,
581- },
582- });
583-
584- // Execute tool calls if any
585- const toolResults: ToolResultCollected[] = [];
586- if (stopReason === "tool_use" && toolCalls.length > 0) {
587- for (const tc of toolCalls) {
588- const executor = toolExecutors.get(tc.name);
589- let result: unknown;
590- let isError = false;
591- if (!executor) {
592- result = `Unknown tool: ${tc.name}`;
593- isError = true;
594- } else {
595- try {
596- result = await executor(tc.args);
597- } catch (err) {
598- result = normalizeUnknownError(err).message;
599- isError = true;
600- }
601- }
602- toolResults.push({
603- toolCallId: tc.id,
604- toolName: tc.name,
605- result,
606- isError,
607- });
608- yield {
609- type: "tool-result",
610- toolCallId: tc.id,
611- toolName: tc.name,
612- result,
613- isError,
614- };
615- }
616- }
617-
618- // Build CoreMessages for this step
619- const stepMessages = buildCoreMessages(
620- assistantText,
621- thinkingBlocks,
622- toolCalls,
623- toolResults,
624- );
625- allNewMessages.push(...stepMessages);
626-
627- // If no tool calls or end of turn, we're done
628- if (stopReason !== "tool_use" || toolCalls.length === 0) {
629- break;
630- }
631-
632- // Append assistant + tool results to conversation for next step
633- const assistantBlocks: ContentBlockParam[] = [];
634- for (const tb of thinkingBlocks) {
635- if (tb.redacted) {
636- assistantBlocks.push({
637- type: "redacted_thinking",
638- data: tb.signature,
639- } as ContentBlockParam);
640- } else if (tb.text.trim() && tb.signature.trim()) {
641- assistantBlocks.push({
642- type: "thinking",
643- thinking: tb.text,
644- signature: tb.signature,
645- } as ContentBlockParam);
646- }
647- }
648- if (assistantText.trim()) {
649- assistantBlocks.push({ type: "text", text: assistantText });
650- }
651- for (const tc of toolCalls) {
652- assistantBlocks.push({
653- type: "tool_use",
654- id: tc.id,
655- name: tc.name,
656- input: tc.args as Record<string, unknown>,
657- });
658- }
659- currentMessages.push({
660- role: "assistant",
661- content: assistantBlocks,
662- });
663-
664- const resultBlocks: ContentBlockParam[] = toolResults.map((tr) => ({
665- type: "tool_result" as const,
666- tool_use_id: tr.toolCallId,
667- content:
668- typeof tr.result === "string"
669- ? tr.result
670- : JSON.stringify(tr.result ?? ""),
671- is_error: tr.isError,
672- }));
673- currentMessages.push({ role: "user", content: resultBlocks });
674- }
675-
676- logApiEvent("turn complete", {
677- newMessagesCount: allNewMessages.length,
678- inputTokens: totalInputTokens,
679- outputTokens: totalOutputTokens,
680- });
681-
682- yield {
683- type: "turn-complete",
684- inputTokens: totalInputTokens,
685- outputTokens: totalOutputTokens,
686- contextTokens,
687- messages: allNewMessages,
688- };
689- } catch (err) {
690- const normalizedError = normalizeUnknownError(err);
691- logApiEvent("turn error", normalizedError);
692- yield {
693- type: "turn-error",
694- error: normalizedError,
695- partialMessages: allNewMessages,
696- };
697- }
698-}