/** * Provider-agnostic AI client types. * * 공통 인터페이스만 정의 — 실제 호출은 provider 별 어댑터에서. */ export type AIRole = 'system' | 'user' | 'assistant'; export interface AITextPart { type: 'text'; text: string; } export type AIImageMediaType = 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'; export interface AIImagePart { type: 'image'; source: { kind: 'base64'; data: Buffer | Uint8Array; mediaType: AIImageMediaType; } | { kind: 'url'; url: string; }; } /** * Assistant 가 tool 을 호출하라고 한 시점의 content part. * 다음 턴에서 같은 id 로 tool_result 를 매핑한다. */ export interface AIToolUsePart { type: 'tool_use'; /** provider-stable id — Anthropic tool_use.id / OpenAI tool_call.id / Gemini 의 자체 매핑 */ id: string; /** tool 이름 */ name: string; /** 호출 인자 (JSON object) */ arguments: Record; /** * provider-specific opaque metadata that must be echoed back when this tool_use * is referenced in subsequent turns. * * Gemini: `thoughtSignature` — 안 보내면 400 에러. * Anthropic: 없음. * OpenAI: 없음. * * 호출자(assistant loop)는 AIToolCall.providerMeta 를 그대로 복사해 넣는다. */ providerMeta?: Record; } /** * 도구 실행 결과를 LLM 에 회신하는 user 측 content part. * * Anthropic: { type: 'tool_result', tool_use_id, content } — user role 에 들어감. * OpenAI: tool role 메시지로 전송. * Gemini: functionResponse part — user role 에 들어감. */ export interface AIToolResultPart { type: 'tool_result'; /** 매핑되는 AIToolUsePart.id */ toolUseId: string; /** 도구 실행 결과 (text 또는 JSON-serializable) */ content: string; /** 실행 중 에러 발생 표시 (LLM 이 retry/대안 판단) */ isError?: boolean; } export type AIContentPart = AITextPart | AIImagePart | AIToolUsePart | AIToolResultPart; export interface AIMessage { role: AIRole; content: string | AIContentPart[]; } export interface AIChatOptions { /** 모델 override (없으면 client 기본값) */ model?: string; maxTokens?: number; temperature?: number; /** * system prompt — messages 의 system 메시지와 합쳐서 전달. * Anthropic 의 system 파라미터 / OpenAI 의 system 메시지로 매핑. */ systemPrompt?: string; stopSequences?: string[]; /** * Told what one provider call used, right after it returns. The metering boundary (aiClientFor) sets this per * call so the usage row knows whose call it was; adapters call it once for every request they send. */ onUsage?: (usage: AIProviderUsage) => void; /** * Stops waiting for the request - a person's stop, or an unattended run's time limit. Every adapter hands it to its * SDK. The provider may still complete and bill a request it already received. */ signal?: AbortSignal; } /** What one provider request used, as the provider reported it. A count the provider did not report stays undefined. */ export interface AIProviderUsage { model: string; /** Every input token, cached ones included (providers/usage.ts). */ inputTokens?: number; /** Every output token, reasoning included. */ outputTokens?: number; /** The part of inputTokens read from the provider's cache. */ cacheReadTokens?: number; /** The part of inputTokens written to the provider's cache. */ cacheWriteTokens?: number; } export interface AIJSONOptions extends AIChatOptions { /** JSON Schema (옵션). 어댑터가 지원하면 structured output 강제 */ schema?: object; } export interface AIVisionOptions extends AIChatOptions { } /** * Provider-agnostic 도구 정의. * Anthropic input_schema / OpenAI parameters / Gemini parameters 로 어댑터에서 정규화. */ export interface AITool { name: string; description: string; /** JSON Schema (object 권장). enum / required / properties 등 표준 키 사용. */ parameters: Record; } /** * LLM 이 호출하라고 지시한 도구 1 건. * id 는 multi-turn 흐름에서 tool_result 매핑에 사용 — 어댑터가 항상 채워야 한다. */ export interface AIToolCall { id: string; name: string; arguments: Record; /** * provider-specific opaque metadata to round-trip on subsequent turns. * Gemini 는 `thoughtSignature` 를 여기에 담는다 — 다음 턴에 functionCall.thoughtSignature * 로 복원되어야 400 에러 회피. */ providerMeta?: Record; } export interface AIToolChatOptions extends AIChatOptions { /** * tool 선택 모드: * - 'auto': LLM 자율 (tool 호출 또는 텍스트 응답) * - 'required': 반드시 하나 이상 tool 호출 * - 'none': tool 무시, 텍스트만 */ toolChoice?: 'auto' | 'required' | 'none'; /** 'required' 와 함께 특정 tool 강제. provider 별 지원 다름. */ forceTool?: string; /** * 병렬 tool 호출 허용 여부 (default true). * false 시 LLM 이 한 번에 하나의 tool 만 호출. */ allowParallelToolCalls?: boolean; } export interface AIToolChatResult { /** 사용자에게 보여줄 텍스트 (tool 호출과 함께 동봉될 수도 있음) */ text?: string; /** LLM 이 호출하라고 지시한 도구들 (병렬 가능) */ toolCalls: AIToolCall[]; /** * 정규화된 stop reason: * 'tool_use' — tool 호출 발생 * 'end_turn' — 텍스트 응답 종료 * 'max_tokens' — 토큰 한도 * 'stop_sequence' — stop sequence 도달 * 기타 — provider 원본 그대로 */ stopReason: 'tool_use' | 'end_turn' | 'max_tokens' | 'stop_sequence' | string; } export interface AIClient { /** 'anthropic:claude-sonnet-4-6' 등 사람이 읽을 식별자 */ readonly id: string; /** 텍스트 chat completion */ chat(messages: AIMessage[], options?: AIChatOptions): Promise; /** JSON 출력 강제. 파싱된 객체 반환. */ generateJSON(prompt: string | AIMessage[], options?: AIJSONOptions): Promise; /** 이미지 입력 — 텍스트 응답. 어댑터가 vision 모델을 지원해야 함. */ vision?(image: Buffer | Uint8Array | { url: string; }, prompt: string, options?: AIVisionOptions): Promise; /** Makes a picture from words (ADR-0226 decision 8). Only providers that make pictures have it. */ generateImage?(prompt: string, options?: AIImageOptions): Promise; /** * Tool calling — LLM 이 자유 텍스트 대신 정의된 도구를 schema-검증된 인자로 호출. * 각 도구의 parameters 가 enum/required 강제 → invalid type / 누락 필드 봉쇄. * 어댑터별로 Anthropic tool_use / OpenAI tools / Gemini functionCalls 로 매핑. */ chatWithTools?(messages: AIMessage[], tools: AITool[], options?: AIToolChatOptions): Promise; /** Optional speech recognition. The provider returns timestamped speech, never inferred video visuals. */ transcribe?(audio: Buffer, options?: AIChatOptions): Promise<{ text: string; segments: { start: number; end: number; text: string; }[]; }>; /** The ids of the conversation models this key may call, sorted. Reading it also proves the key is accepted. */ listModels(): Promise; } /** What a made picture asks for (ADR-0226 decision 8-1). */ export interface AIImageOptions { /** The image model; the agent's image model when not given. */ model?: string; /** low, medium or high - the provider's quality steps where it has them. */ quality?: 'low' | 'medium' | 'high'; /** WIDTHxHEIGHT, e.g. 1024x1024. */ size?: string; onUsage?: (usage: AIProviderUsage) => void; } /** A made picture. */ export interface AIImage { data: Buffer; mimetype: string; /** The model that made it, as the provider said. */ model: string; } export interface AIClientConfig { /** 등록된 provider 이름 (예: 'anthropic', 'openai', 'gemini') */ provider: string; /** The model every call uses unless a call names another. */ model?: string; /** Required - a provider is never reached with a key from the process environment. */ apiKey: string; /** OpenAI organization (provider:'openai' 전용) */ organization?: string; baseURL?: string; [k: string]: any; } export type AIProviderFactory = (config: AIClientConfig) => AIClient;