Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 4 additions & 73 deletions packages/claude-sdk/src/private/AgentRun.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import { randomUUID } from 'node:crypto';
import type { MessagePort } from 'node:worker_threads';
import type { Anthropic } from '@anthropic-ai/sdk';
import type { BetaMessageStreamParams } from '@anthropic-ai/sdk/resources/beta/messages.js';
import type { BetaCacheControlEphemeral, BetaClearThinking20251015Edit, BetaClearToolUses20250919Edit, BetaCompact20260112Edit, BetaCompactionBlockParam, BetaContextManagementConfig, BetaTextBlockParam, BetaThinkingBlockParam, BetaToolUnion, BetaToolUseBlockParam } from '@anthropic-ai/sdk/resources/beta.mjs';
import { AnthropicBeta } from '../public/enums';
import type { BetaCompactionBlockParam, BetaTextBlockParam, BetaThinkingBlockParam, BetaToolUseBlockParam } from '@anthropic-ai/sdk/resources/beta.mjs';
import type { AnyToolDefinition, ILogger, RunAgentQuery, SdkMessage } from '../public/types';
import { AgentChannel } from './AgentChannel';
import { ApprovalState } from './ApprovalState';
import type { ConversationStore } from './ConversationStore';
import { AGENT_SDK_PREFIX } from './consts';
import { MessageStream } from './MessageStream';
import { calculateCost, getContextWindow } from './pricing';
import { buildRequestParams } from './RequestBuilder';
import type { ContentBlock, MessageStreamResult, ToolUseResult } from './types';

export class AgentRun {
Expand Down Expand Up @@ -140,71 +138,12 @@ export class AgentRun {
}

#getMessageStream(messages: Anthropic.Beta.Messages.BetaMessageParam[]) {
const tools: BetaToolUnion[] = this.#options.tools.map(
(t) =>
({
name: t.name,
description: t.description,
input_schema: t.input_schema.toJSONSchema({ target: 'draft-07', io: 'input' }) as Anthropic.Tool['input_schema'],
input_examples: t.input_examples,
}) satisfies BetaToolUnion,
);

const betas = resolveCapabilities(this.#options.betas, AnthropicBeta);

const context_management: BetaContextManagementConfig = {
edits: [],
};
if (betas[AnthropicBeta.ContextManagement]) {
context_management.edits?.push({ type: 'clear_thinking_20251015' } satisfies BetaClearThinking20251015Edit);
context_management.edits?.push({ type: 'clear_tool_uses_20250919' } satisfies BetaClearToolUses20250919Edit);
}
if (betas[AnthropicBeta.Compact]) {
context_management.edits?.push({
type: 'compact_20260112',
pause_after_compaction: this.#options.pauseAfterCompact ?? false,
trigger: this.#options.compactInputTokens
? {
type: 'input_tokens',
value: this.#options.compactInputTokens,
}
: null,
} satisfies BetaCompact20260112Edit);
}

const systemPrompts = [AGENT_SDK_PREFIX, ...(this.#options.systemPrompts ?? [])];

const body: BetaMessageStreamParams = {
model: this.#options.model,
max_tokens: this.#options.maxTokens,
tools,
context_management,
system: systemPrompts.map((text) => ({ type: 'text', text })),

messages,
// thinking: { type: 'adaptive' },
stream: true,
} satisfies BetaMessageStreamParams;

if (betas[AnthropicBeta.PromptCachingScope]) {
body.cache_control = { type: 'ephemeral', scope: 'global' } as BetaCacheControlEphemeral;
}
if (this.#options.thinking === true) {
body.thinking = { type: 'adaptive' };
}

const anthropicBetas = Object.entries(betas)
.filter(([, enabled]) => enabled)
.map(([beta]) => beta)
.join(',');

const { body, headers } = buildRequestParams(this.#options, messages);
const requestOptions = {
headers: { 'anthropic-beta': anthropicBetas },
headers,
signal: this.#abortController.signal,
} satisfies Anthropic.RequestOptions;

this.#logger?.info('Sending request', body);

return this.#client.beta.messages.stream(body, requestOptions);
}

Expand Down Expand Up @@ -296,11 +235,3 @@ export class AgentRun {
}
}
}

function resolveCapabilities<T extends string>(partial: Partial<Record<T, boolean>> | undefined, enumObj: Record<string, T>): Record<T, boolean> {
const result = {} as Record<T, boolean>;
for (const key of Object.values(enumObj)) {
result[key] = partial?.[key] ?? false;
}
return result;
}
89 changes: 89 additions & 0 deletions packages/claude-sdk/src/private/RequestBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import type { Anthropic } from '@anthropic-ai/sdk';
import type { BetaMessageStreamParams } from '@anthropic-ai/sdk/resources/beta/messages.js';
import type { BetaCacheControlEphemeral, BetaClearThinking20251015Edit, BetaClearToolUses20250919Edit, BetaCompact20260112Edit, BetaContextManagementConfig, BetaToolUnion } from '@anthropic-ai/sdk/resources/beta.mjs';
import { AnthropicBeta } from '../public/enums';
import type { RunAgentQuery } from '../public/types';
import { AGENT_SDK_PREFIX } from './consts';

export type RequestParams = {
body: BetaMessageStreamParams;
headers: { 'anthropic-beta': string };
};

/**
* Pure function — builds the Anthropic API request params from agent options
* and the current message list. No I/O, no client reference, no signal.
*
* AgentRun calls this and adds the AbortSignal before passing to the client,
* since the signal is tied to AgentRun's abort lifecycle.
*/
export function buildRequestParams(options: RunAgentQuery, messages: Anthropic.Beta.Messages.BetaMessageParam[]): RequestParams {
const tools: BetaToolUnion[] = options.tools.map(
(t) =>
({
name: t.name,
description: t.description,
input_schema: t.input_schema.toJSONSchema({ target: 'draft-07', io: 'input' }) as Anthropic.Tool['input_schema'],
input_examples: t.input_examples,
}) satisfies BetaToolUnion,
);

const betas = resolveCapabilities(options.betas, AnthropicBeta);

const context_management: BetaContextManagementConfig = {
edits: [],
};
if (betas[AnthropicBeta.ContextManagement]) {
context_management.edits?.push({ type: 'clear_thinking_20251015' } satisfies BetaClearThinking20251015Edit);
context_management.edits?.push({ type: 'clear_tool_uses_20250919' } satisfies BetaClearToolUses20250919Edit);
}
if (betas[AnthropicBeta.Compact]) {
context_management.edits?.push({
type: 'compact_20260112',
pause_after_compaction: options.pauseAfterCompact ?? false,
trigger: options.compactInputTokens
? {
type: 'input_tokens',
value: options.compactInputTokens,
}
: null,
} satisfies BetaCompact20260112Edit);
}

const systemPrompts = [AGENT_SDK_PREFIX, ...(options.systemPrompts ?? [])];

const body: BetaMessageStreamParams = {
model: options.model,
max_tokens: options.maxTokens,
tools,
context_management,
system: systemPrompts.map((text) => ({ type: 'text', text })),
messages,
stream: true,
} satisfies BetaMessageStreamParams;

if (betas[AnthropicBeta.PromptCachingScope]) {
body.cache_control = { type: 'ephemeral', scope: 'global' } as BetaCacheControlEphemeral;
}
if (options.thinking === true) {
body.thinking = { type: 'adaptive' };
}

const anthropicBetas = Object.entries(betas)
.filter(([, enabled]) => enabled)
.map(([beta]) => beta)
.join(',');

return {
body,
headers: { 'anthropic-beta': anthropicBetas },
};
}

function resolveCapabilities<T extends string>(partial: Partial<Record<T, boolean>> | undefined, enumObj: Record<string, T>): Record<T, boolean> {
const result = {} as Record<T, boolean>;
for (const key of Object.values(enumObj)) {
result[key] = partial?.[key] ?? false;
}
return result;
}
Loading
Loading