@yuva-devlab/ai-client 0.2.6 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -24,6 +24,8 @@ declare const AI_ENDPOINTS: Readonly<{
24
24
  ANTHROPIC_DEFAULT_BASE_URL: "https://api.anthropic.com/v1";
25
25
  /** Google Gemini Generative Language v1beta endpoint */
26
26
  GOOGLE_GEMINI_DEFAULT_BASE_URL: "https://generativelanguage.googleapis.com/v1beta";
27
+ /** Cline API Gateway v1 chat completions endpoint */
28
+ CLINE_DEFAULT_BASE_URL: "https://api.cline.bot/api/v1";
27
29
  /** Required Anthropic API version header value */
28
30
  ANTHROPIC_VERSION_HEADER: "2023-06-01";
29
31
  }>;
@@ -50,6 +52,8 @@ declare const AI_DEFAULT_MODELS: Readonly<{
50
52
  OPENAI: "gpt-4o-mini";
51
53
  /** Default Anthropic Claude model */
52
54
  ANTHROPIC: "claude-3-5-haiku-latest";
55
+ /** Default Cline API Gateway model (NVIDIA 120B reasoning model, free tier) */
56
+ CLINE: "nvidia/nemotron-3.5-super-vl:free";
53
57
  }>;
54
58
 
55
59
  /**
@@ -1111,6 +1115,128 @@ declare class AnthropicAdapter implements ILLMProvider {
1111
1115
  stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
1112
1116
  }
1113
1117
 
1118
+ /**
1119
+ * @file packages/ai-client/src/adapters/cline/cline.types.ts
1120
+ * @description Wire types, configuration interfaces, and tool name normalization helpers for Cline API.
1121
+ * @module @yuva-devlab/ai-client
1122
+ */
1123
+
1124
+ /**
1125
+ * Configuration options for initializing the ClineAdapter.
1126
+ */
1127
+ interface ClineAdapterConfig {
1128
+ /** Cline API Gateway authentication key */
1129
+ apiKey?: string;
1130
+ /** Custom base URL (defaults to AI_ENDPOINTS.CLINE_DEFAULT_BASE_URL) */
1131
+ baseUrl?: string;
1132
+ /** Default model identifier (defaults to AI_DEFAULT_MODELS.CLINE) */
1133
+ defaultModel?: string;
1134
+ /** Optional dynamic credential resolver for secret managers */
1135
+ credentials?: CredentialResolver;
1136
+ }
1137
+ /**
1138
+ * Expected response structure from Cline Chat Completions endpoint.
1139
+ */
1140
+ interface ClineCompletionResponse {
1141
+ /** Completion candidates list */
1142
+ choices?: Array<{
1143
+ message?: {
1144
+ content?: string | null;
1145
+ tool_calls?: Array<{
1146
+ id?: string;
1147
+ type?: string;
1148
+ function?: {
1149
+ name?: string;
1150
+ arguments?: string;
1151
+ };
1152
+ }>;
1153
+ };
1154
+ finish_reason?: string | null;
1155
+ }>;
1156
+ /** Data envelope wrapper when returned by certain Cline gateway routes */
1157
+ data?: {
1158
+ choices?: ClineCompletionResponse["choices"];
1159
+ };
1160
+ /** Token accounting and usage details */
1161
+ usage?: {
1162
+ prompt_tokens?: number;
1163
+ completion_tokens?: number;
1164
+ total_tokens?: number;
1165
+ };
1166
+ }
1167
+ /**
1168
+ * Normalizes a canonical tool name to OpenAPI specification pattern (alphanumeric and underscores only).
1169
+ * Converts dots to underscores (e.g. "transactions.create" -> "transactions_create").
1170
+ *
1171
+ * @param name - Canonical tool name with domain dot separators.
1172
+ * @returns OpenAPI-compliant tool name.
1173
+ */
1174
+ declare function sanitizeClineToolName(name: string): string;
1175
+ /**
1176
+ * Restores canonical tool name from OpenAPI normalized string.
1177
+ * Converts underscores to dots (e.g. "transactions_create" -> "transactions.create").
1178
+ *
1179
+ * @param name - Normalized tool name from model invocation.
1180
+ * @returns Canonical tool name.
1181
+ */
1182
+ declare function restoreClineToolName(name: string): string;
1183
+ /**
1184
+ * Converts canonical messages to Cline/OpenAI wire format.
1185
+ *
1186
+ * @param messages - Canonical conversation history turns.
1187
+ * @returns Array of OpenAI-compatible wire messages.
1188
+ */
1189
+ declare function mapClineMessages(messages: LLMRequest["messages"]): {
1190
+ role: string;
1191
+ content: string;
1192
+ }[];
1193
+
1194
+ /**
1195
+ * @file packages/ai-client/src/adapters/cline/cline.adapter.ts
1196
+ * @description Standard Cline API Gateway adapter supporting Nemotron, Solar, DeepSeek, and Qwen.
1197
+ * @module @yuva-devlab/ai-client
1198
+ */
1199
+
1200
+ /**
1201
+ * Cline adapter executing completions and streaming via the Cline API Gateway.
1202
+ */
1203
+ declare class ClineAdapter implements ILLMProvider {
1204
+ readonly name = "cline";
1205
+ private readonly config;
1206
+ constructor(config?: ClineAdapterConfig);
1207
+ private resolveCredentials;
1208
+ complete(request: LLMRequest): Promise<LLMResponse>;
1209
+ stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
1210
+ }
1211
+
1212
+ /**
1213
+ * @file packages/ai-client/src/adapters/cline/cline.helpers.ts
1214
+ * @description Helper functions for Cline completion parsing, error mapping, and tool extraction.
1215
+ * @module @yuva-devlab/ai-client
1216
+ */
1217
+
1218
+ /**
1219
+ * Parses and restores canonical tool calls from Cline model output.
1220
+ *
1221
+ * @param choices - Candidate completions from Cline API.
1222
+ * @returns Array of parsed ToolCall objects or undefined.
1223
+ */
1224
+ declare function extractClineToolCalls(choices?: ClineCompletionResponse["choices"]): ToolCall[] | undefined;
1225
+ /**
1226
+ * Maps raw finish_reason string to canonical FinishReason enum.
1227
+ *
1228
+ * @param reason - Raw finish reason from API response.
1229
+ * @returns Canonical FinishReason member.
1230
+ */
1231
+ declare function mapClineFinishReason(reason?: string | null): FinishReason;
1232
+ /**
1233
+ * Extracts rate limit reset delays or retry-after headers from HTTP response.
1234
+ *
1235
+ * @param response - Fetch response instance.
1236
+ * @returns Informational suffix string or empty string.
1237
+ */
1238
+ declare function extractClineRetrySuffix(response: Response): string;
1239
+
1114
1240
  /**
1115
1241
  * @file packages/ai-client/src/cascade/fallback-cascade.ts
1116
1242
  * @description Intelligent multi-tier fallback cascade routing across local and cloud providers.
@@ -1213,7 +1339,7 @@ declare function extractStructuredOutput<T>(options: ExtractStructuredOutputOpti
1213
1339
  /**
1214
1340
  * Standard provider type identifiers.
1215
1341
  */
1216
- type ProviderType = "ollama" | "groq" | "google" | "openai" | "anthropic" | "cascade";
1342
+ type ProviderType = "ollama" | "groq" | "google" | "openai" | "anthropic" | "cline" | "cascade";
1217
1343
  /**
1218
1344
  * Creates an instance of an LLM provider adapter matching the specified type.
1219
1345
  *
@@ -1242,6 +1368,8 @@ interface CascadeCandidatesConfig {
1242
1368
  openai?: Record<string, unknown>;
1243
1369
  /** Optional Anthropic credentials and configuration */
1244
1370
  anthropic?: Record<string, unknown>;
1371
+ /** Optional Cline API Gateway credentials and configuration */
1372
+ cline?: Record<string, unknown>;
1245
1373
  }
1246
1374
  /**
1247
1375
  * Builds an ordered cascade of provider candidates based on explicit consumer configuration.
@@ -1275,4 +1403,4 @@ interface DefaultProviderOptions {
1275
1403
  */
1276
1404
  declare function createDefaultProvider(options?: DefaultProviderOptions): ILLMProvider;
1277
1405
 
1278
- export { type AIMessage, AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, type AnthropicAdapterConfig, type AnthropicResponse, type CascadeCandidatesConfig, type CredentialResolver, type DefaultProviderOptions, type ExtractStructuredOutputOptions, FallbackCascade, type FallbackCascadeOptions, FinishReason, type GeminiCandidate, type GeminiResponse, GoogleAdapter, type GoogleAdapterConfig, GroqAdapter, type GroqAdapterConfig, type GroqCompletionResponse, type ILLMProvider, type LLMRequest, type LLMRequestOptions, LLMRequestOptionsSchema, LLMRequestSchema, type LLMResponse, LLMResponseSchema, type LLMStreamChunk, type LLMUsage, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, type OllamaAdapterConfig, type OllamaChatResponseChunk, type OllamaWireMessage, OpenAIAdapter, type OpenAIAdapterConfig, type OpenAiCompletionResponse, type OpenAiWireMessage, type ProviderCredentials, type ProviderType, type ToolCall, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractStructuredOutput, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials };
1406
+ export { type AIMessage, AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, type AnthropicAdapterConfig, type AnthropicResponse, type CascadeCandidatesConfig, ClineAdapter, type ClineAdapterConfig, type ClineCompletionResponse, type CredentialResolver, type DefaultProviderOptions, type ExtractStructuredOutputOptions, FallbackCascade, type FallbackCascadeOptions, FinishReason, type GeminiCandidate, type GeminiResponse, GoogleAdapter, type GoogleAdapterConfig, GroqAdapter, type GroqAdapterConfig, type GroqCompletionResponse, type ILLMProvider, type LLMRequest, type LLMRequestOptions, LLMRequestOptionsSchema, LLMRequestSchema, type LLMResponse, LLMResponseSchema, type LLMStreamChunk, type LLMUsage, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, type OllamaAdapterConfig, type OllamaChatResponseChunk, type OllamaWireMessage, OpenAIAdapter, type OpenAIAdapterConfig, type OpenAiCompletionResponse, type OpenAiWireMessage, type ProviderCredentials, type ProviderType, type ToolCall, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractClineRetrySuffix, extractClineToolCalls, extractStructuredOutput, mapClineFinishReason, mapClineMessages, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials, restoreClineToolName, sanitizeClineToolName };
package/dist/index.d.ts CHANGED
@@ -24,6 +24,8 @@ declare const AI_ENDPOINTS: Readonly<{
24
24
  ANTHROPIC_DEFAULT_BASE_URL: "https://api.anthropic.com/v1";
25
25
  /** Google Gemini Generative Language v1beta endpoint */
26
26
  GOOGLE_GEMINI_DEFAULT_BASE_URL: "https://generativelanguage.googleapis.com/v1beta";
27
+ /** Cline API Gateway v1 chat completions endpoint */
28
+ CLINE_DEFAULT_BASE_URL: "https://api.cline.bot/api/v1";
27
29
  /** Required Anthropic API version header value */
28
30
  ANTHROPIC_VERSION_HEADER: "2023-06-01";
29
31
  }>;
@@ -50,6 +52,8 @@ declare const AI_DEFAULT_MODELS: Readonly<{
50
52
  OPENAI: "gpt-4o-mini";
51
53
  /** Default Anthropic Claude model */
52
54
  ANTHROPIC: "claude-3-5-haiku-latest";
55
+ /** Default Cline API Gateway model (NVIDIA 120B reasoning model, free tier) */
56
+ CLINE: "nvidia/nemotron-3.5-super-vl:free";
53
57
  }>;
54
58
 
55
59
  /**
@@ -1111,6 +1115,128 @@ declare class AnthropicAdapter implements ILLMProvider {
1111
1115
  stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
1112
1116
  }
1113
1117
 
1118
+ /**
1119
+ * @file packages/ai-client/src/adapters/cline/cline.types.ts
1120
+ * @description Wire types, configuration interfaces, and tool name normalization helpers for Cline API.
1121
+ * @module @yuva-devlab/ai-client
1122
+ */
1123
+
1124
+ /**
1125
+ * Configuration options for initializing the ClineAdapter.
1126
+ */
1127
+ interface ClineAdapterConfig {
1128
+ /** Cline API Gateway authentication key */
1129
+ apiKey?: string;
1130
+ /** Custom base URL (defaults to AI_ENDPOINTS.CLINE_DEFAULT_BASE_URL) */
1131
+ baseUrl?: string;
1132
+ /** Default model identifier (defaults to AI_DEFAULT_MODELS.CLINE) */
1133
+ defaultModel?: string;
1134
+ /** Optional dynamic credential resolver for secret managers */
1135
+ credentials?: CredentialResolver;
1136
+ }
1137
+ /**
1138
+ * Expected response structure from Cline Chat Completions endpoint.
1139
+ */
1140
+ interface ClineCompletionResponse {
1141
+ /** Completion candidates list */
1142
+ choices?: Array<{
1143
+ message?: {
1144
+ content?: string | null;
1145
+ tool_calls?: Array<{
1146
+ id?: string;
1147
+ type?: string;
1148
+ function?: {
1149
+ name?: string;
1150
+ arguments?: string;
1151
+ };
1152
+ }>;
1153
+ };
1154
+ finish_reason?: string | null;
1155
+ }>;
1156
+ /** Data envelope wrapper when returned by certain Cline gateway routes */
1157
+ data?: {
1158
+ choices?: ClineCompletionResponse["choices"];
1159
+ };
1160
+ /** Token accounting and usage details */
1161
+ usage?: {
1162
+ prompt_tokens?: number;
1163
+ completion_tokens?: number;
1164
+ total_tokens?: number;
1165
+ };
1166
+ }
1167
+ /**
1168
+ * Normalizes a canonical tool name to OpenAPI specification pattern (alphanumeric and underscores only).
1169
+ * Converts dots to underscores (e.g. "transactions.create" -> "transactions_create").
1170
+ *
1171
+ * @param name - Canonical tool name with domain dot separators.
1172
+ * @returns OpenAPI-compliant tool name.
1173
+ */
1174
+ declare function sanitizeClineToolName(name: string): string;
1175
+ /**
1176
+ * Restores canonical tool name from OpenAPI normalized string.
1177
+ * Converts underscores to dots (e.g. "transactions_create" -> "transactions.create").
1178
+ *
1179
+ * @param name - Normalized tool name from model invocation.
1180
+ * @returns Canonical tool name.
1181
+ */
1182
+ declare function restoreClineToolName(name: string): string;
1183
+ /**
1184
+ * Converts canonical messages to Cline/OpenAI wire format.
1185
+ *
1186
+ * @param messages - Canonical conversation history turns.
1187
+ * @returns Array of OpenAI-compatible wire messages.
1188
+ */
1189
+ declare function mapClineMessages(messages: LLMRequest["messages"]): {
1190
+ role: string;
1191
+ content: string;
1192
+ }[];
1193
+
1194
+ /**
1195
+ * @file packages/ai-client/src/adapters/cline/cline.adapter.ts
1196
+ * @description Standard Cline API Gateway adapter supporting Nemotron, Solar, DeepSeek, and Qwen.
1197
+ * @module @yuva-devlab/ai-client
1198
+ */
1199
+
1200
+ /**
1201
+ * Cline adapter executing completions and streaming via the Cline API Gateway.
1202
+ */
1203
+ declare class ClineAdapter implements ILLMProvider {
1204
+ readonly name = "cline";
1205
+ private readonly config;
1206
+ constructor(config?: ClineAdapterConfig);
1207
+ private resolveCredentials;
1208
+ complete(request: LLMRequest): Promise<LLMResponse>;
1209
+ stream(request: LLMRequest): AsyncIterable<LLMStreamChunk>;
1210
+ }
1211
+
1212
+ /**
1213
+ * @file packages/ai-client/src/adapters/cline/cline.helpers.ts
1214
+ * @description Helper functions for Cline completion parsing, error mapping, and tool extraction.
1215
+ * @module @yuva-devlab/ai-client
1216
+ */
1217
+
1218
+ /**
1219
+ * Parses and restores canonical tool calls from Cline model output.
1220
+ *
1221
+ * @param choices - Candidate completions from Cline API.
1222
+ * @returns Array of parsed ToolCall objects or undefined.
1223
+ */
1224
+ declare function extractClineToolCalls(choices?: ClineCompletionResponse["choices"]): ToolCall[] | undefined;
1225
+ /**
1226
+ * Maps raw finish_reason string to canonical FinishReason enum.
1227
+ *
1228
+ * @param reason - Raw finish reason from API response.
1229
+ * @returns Canonical FinishReason member.
1230
+ */
1231
+ declare function mapClineFinishReason(reason?: string | null): FinishReason;
1232
+ /**
1233
+ * Extracts rate limit reset delays or retry-after headers from HTTP response.
1234
+ *
1235
+ * @param response - Fetch response instance.
1236
+ * @returns Informational suffix string or empty string.
1237
+ */
1238
+ declare function extractClineRetrySuffix(response: Response): string;
1239
+
1114
1240
  /**
1115
1241
  * @file packages/ai-client/src/cascade/fallback-cascade.ts
1116
1242
  * @description Intelligent multi-tier fallback cascade routing across local and cloud providers.
@@ -1213,7 +1339,7 @@ declare function extractStructuredOutput<T>(options: ExtractStructuredOutputOpti
1213
1339
  /**
1214
1340
  * Standard provider type identifiers.
1215
1341
  */
1216
- type ProviderType = "ollama" | "groq" | "google" | "openai" | "anthropic" | "cascade";
1342
+ type ProviderType = "ollama" | "groq" | "google" | "openai" | "anthropic" | "cline" | "cascade";
1217
1343
  /**
1218
1344
  * Creates an instance of an LLM provider adapter matching the specified type.
1219
1345
  *
@@ -1242,6 +1368,8 @@ interface CascadeCandidatesConfig {
1242
1368
  openai?: Record<string, unknown>;
1243
1369
  /** Optional Anthropic credentials and configuration */
1244
1370
  anthropic?: Record<string, unknown>;
1371
+ /** Optional Cline API Gateway credentials and configuration */
1372
+ cline?: Record<string, unknown>;
1245
1373
  }
1246
1374
  /**
1247
1375
  * Builds an ordered cascade of provider candidates based on explicit consumer configuration.
@@ -1275,4 +1403,4 @@ interface DefaultProviderOptions {
1275
1403
  */
1276
1404
  declare function createDefaultProvider(options?: DefaultProviderOptions): ILLMProvider;
1277
1405
 
1278
- export { type AIMessage, AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, type AnthropicAdapterConfig, type AnthropicResponse, type CascadeCandidatesConfig, type CredentialResolver, type DefaultProviderOptions, type ExtractStructuredOutputOptions, FallbackCascade, type FallbackCascadeOptions, FinishReason, type GeminiCandidate, type GeminiResponse, GoogleAdapter, type GoogleAdapterConfig, GroqAdapter, type GroqAdapterConfig, type GroqCompletionResponse, type ILLMProvider, type LLMRequest, type LLMRequestOptions, LLMRequestOptionsSchema, LLMRequestSchema, type LLMResponse, LLMResponseSchema, type LLMStreamChunk, type LLMUsage, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, type OllamaAdapterConfig, type OllamaChatResponseChunk, type OllamaWireMessage, OpenAIAdapter, type OpenAIAdapterConfig, type OpenAiCompletionResponse, type OpenAiWireMessage, type ProviderCredentials, type ProviderType, type ToolCall, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractStructuredOutput, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials };
1406
+ export { type AIMessage, AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, type AnthropicAdapterConfig, type AnthropicResponse, type CascadeCandidatesConfig, ClineAdapter, type ClineAdapterConfig, type ClineCompletionResponse, type CredentialResolver, type DefaultProviderOptions, type ExtractStructuredOutputOptions, FallbackCascade, type FallbackCascadeOptions, FinishReason, type GeminiCandidate, type GeminiResponse, GoogleAdapter, type GoogleAdapterConfig, GroqAdapter, type GroqAdapterConfig, type GroqCompletionResponse, type ILLMProvider, type LLMRequest, type LLMRequestOptions, LLMRequestOptionsSchema, LLMRequestSchema, type LLMResponse, LLMResponseSchema, type LLMStreamChunk, type LLMUsage, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, type OllamaAdapterConfig, type OllamaChatResponseChunk, type OllamaWireMessage, OpenAIAdapter, type OpenAIAdapterConfig, type OpenAiCompletionResponse, type OpenAiWireMessage, type ProviderCredentials, type ProviderType, type ToolCall, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractClineRetrySuffix, extractClineToolCalls, extractStructuredOutput, mapClineFinishReason, mapClineMessages, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials, restoreClineToolName, sanitizeClineToolName };
package/dist/index.js CHANGED
@@ -14,6 +14,8 @@ var AI_ENDPOINTS = Object.freeze({
14
14
  ANTHROPIC_DEFAULT_BASE_URL: "https://api.anthropic.com/v1",
15
15
  /** Google Gemini Generative Language v1beta endpoint */
16
16
  GOOGLE_GEMINI_DEFAULT_BASE_URL: "https://generativelanguage.googleapis.com/v1beta",
17
+ /** Cline API Gateway v1 chat completions endpoint */
18
+ CLINE_DEFAULT_BASE_URL: "https://api.cline.bot/api/v1",
17
19
  /** Required Anthropic API version header value */
18
20
  ANTHROPIC_VERSION_HEADER: "2023-06-01"
19
21
  });
@@ -29,7 +31,9 @@ var AI_DEFAULT_MODELS = Object.freeze({
29
31
  /** Default OpenAI model */
30
32
  OPENAI: "gpt-4o-mini",
31
33
  /** Default Anthropic Claude model */
32
- ANTHROPIC: "claude-3-5-haiku-latest"
34
+ ANTHROPIC: "claude-3-5-haiku-latest",
35
+ /** Default Cline API Gateway model (NVIDIA 120B reasoning model, free tier) */
36
+ CLINE: "nvidia/nemotron-3.5-super-vl:free"
33
37
  });
34
38
 
35
39
  // src/constants/execution.constants.ts
@@ -511,10 +515,13 @@ var GroqAdapter = class {
511
515
  })
512
516
  });
513
517
  if (!response.ok || !response.body) {
518
+ const errorText = await response.text().catch(() => "");
519
+ const retryAfter = response.headers.get("retry-after") ?? response.headers.get("x-ratelimit-reset-tokens");
520
+ const retryDetail = retryAfter ? ` (retry-after: ${retryAfter})` : "";
514
521
  throw new DomainError(
515
- `Groq streaming error HTTP ${response.status}`,
516
- ErrorCode.MODEL_PROVIDER_ERROR,
517
- 502
522
+ `Groq streaming error HTTP ${response.status}${retryDetail}${errorText ? `: ${errorText}` : ""}`,
523
+ response.status === 429 ? ErrorCode.MODEL_RATE_LIMIT : ErrorCode.MODEL_PROVIDER_ERROR,
524
+ response.status
518
525
  );
519
526
  }
520
527
  const reader = response.body.getReader();
@@ -1038,7 +1045,195 @@ var AnthropicAdapter = class {
1038
1045
  };
1039
1046
  }
1040
1047
  };
1041
- var logger6 = loggerWithConfig(new Logger("FallbackCascade"));
1048
+
1049
+ // src/adapters/cline/cline.types.ts
1050
+ function sanitizeClineToolName(name) {
1051
+ return name.replace(/\./g, "_");
1052
+ }
1053
+ function restoreClineToolName(name) {
1054
+ return name.replace(/_/g, ".");
1055
+ }
1056
+ function mapClineMessages(messages) {
1057
+ return messages.map((m) => ({
1058
+ role: m.role === MessageRole.SYSTEM ? "system" : m.role === MessageRole.ASSISTANT ? "assistant" : "user",
1059
+ content: m.content
1060
+ }));
1061
+ }
1062
+
1063
+ // src/adapters/cline/cline.helpers.ts
1064
+ function extractClineToolCalls(choices) {
1065
+ const choice = choices?.[0];
1066
+ const toolCalls = choice?.message?.tool_calls;
1067
+ if (!toolCalls || toolCalls.length === 0) {
1068
+ return void 0;
1069
+ }
1070
+ return toolCalls.map((tc, index) => {
1071
+ let args = {};
1072
+ try {
1073
+ args = tc.function?.arguments ? JSON.parse(tc.function.arguments) : {};
1074
+ } catch {
1075
+ args = {};
1076
+ }
1077
+ return {
1078
+ id: tc.id ?? `call_${index}`,
1079
+ name: restoreClineToolName(tc.function?.name ?? ""),
1080
+ arguments: args
1081
+ };
1082
+ });
1083
+ }
1084
+ function mapClineFinishReason(reason) {
1085
+ if (reason === "tool_calls") return FinishReason.TOOL_CALLS;
1086
+ if (reason === "length") return FinishReason.LENGTH;
1087
+ return FinishReason.STOP;
1088
+ }
1089
+ function extractClineRetrySuffix(response) {
1090
+ const retryAfter = response.headers.get("retry-after") ?? response.headers.get("x-ratelimit-reset-tokens");
1091
+ return retryAfter ? ` (retry-after: ${retryAfter})` : "";
1092
+ }
1093
+
1094
+ // src/adapters/cline/cline.adapter.ts
1095
+ var logger6 = loggerWithConfig(new Logger("ClineAdapter"));
1096
+ var ClineAdapter = class {
1097
+ name = "cline";
1098
+ config;
1099
+ constructor(config = {}) {
1100
+ this.config = config;
1101
+ }
1102
+ async resolveCredentials() {
1103
+ const dynamic = this.config.credentials ? await this.config.credentials() : {};
1104
+ const apiKey = this.config.apiKey ?? dynamic.apiKey;
1105
+ const baseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? AI_ENDPOINTS.CLINE_DEFAULT_BASE_URL).replace(/\/+$/, "");
1106
+ const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? AI_DEFAULT_MODELS.CLINE;
1107
+ if (!apiKey) {
1108
+ throw new MissingCredentialError("Cline", "apiKey");
1109
+ }
1110
+ return { apiKey, baseUrl, defaultModel };
1111
+ }
1112
+ async complete(request) {
1113
+ const { apiKey, baseUrl, defaultModel } = await this.resolveCredentials();
1114
+ const startTime = Date.now();
1115
+ const model = request.model || defaultModel;
1116
+ logger6.debug("[complete] Executing Cline completion", { model, baseUrl });
1117
+ const controller = new AbortController();
1118
+ const timeout = setTimeout(() => controller.abort(), request.timeoutMs);
1119
+ try {
1120
+ const response = await fetch(`${baseUrl}/chat/completions`, {
1121
+ method: "POST",
1122
+ headers: {
1123
+ "Content-Type": "application/json",
1124
+ Authorization: `Bearer ${apiKey}`
1125
+ },
1126
+ body: JSON.stringify({
1127
+ model,
1128
+ messages: mapClineMessages(request.messages),
1129
+ temperature: request.temperature,
1130
+ max_tokens: request.maxTokens,
1131
+ top_p: request.topP,
1132
+ stop: request.stop,
1133
+ response_format: request.responseFormat === "json_object" ? { type: "json_object" } : void 0
1134
+ }),
1135
+ signal: controller.signal
1136
+ });
1137
+ if (!response.ok) {
1138
+ const errorText = await response.text().catch(() => "");
1139
+ const suffix = extractClineRetrySuffix(response);
1140
+ logger6.error("[complete] Cline API error response", {
1141
+ status: response.status,
1142
+ errorText
1143
+ });
1144
+ throw new DomainError(
1145
+ `Cline returned HTTP ${response.status}: ${errorText}${suffix}`,
1146
+ response.status === 429 ? ErrorCode.MODEL_RATE_LIMIT : ErrorCode.MODEL_PROVIDER_ERROR,
1147
+ response.status
1148
+ );
1149
+ }
1150
+ const raw = await response.json();
1151
+ const choices = raw.choices ?? raw.data?.choices ?? [];
1152
+ const choice = choices[0];
1153
+ const text = choice?.message?.content ?? "";
1154
+ const toolCalls = extractClineToolCalls(choices);
1155
+ const durationMs = Date.now() - startTime;
1156
+ return {
1157
+ text,
1158
+ finishReason: mapClineFinishReason(choice?.finish_reason),
1159
+ usage: {
1160
+ promptTokens: raw.usage?.prompt_tokens ?? 0,
1161
+ completionTokens: raw.usage?.completion_tokens ?? 0,
1162
+ totalTokens: raw.usage?.total_tokens ?? 0
1163
+ },
1164
+ toolCalls,
1165
+ model,
1166
+ durationMs
1167
+ };
1168
+ } catch (err) {
1169
+ if (err instanceof Error && err.name === "AbortError") {
1170
+ logger6.warn("[complete] Cline request timed out", {
1171
+ model,
1172
+ timeoutMs: request.timeoutMs
1173
+ });
1174
+ throw new ModelTimeoutError(model, request.timeoutMs);
1175
+ }
1176
+ throw err;
1177
+ } finally {
1178
+ clearTimeout(timeout);
1179
+ }
1180
+ }
1181
+ async *stream(request) {
1182
+ const { apiKey, baseUrl, defaultModel } = await this.resolveCredentials();
1183
+ const model = request.model || defaultModel;
1184
+ const response = await fetch(`${baseUrl}/chat/completions`, {
1185
+ method: "POST",
1186
+ headers: {
1187
+ "Content-Type": "application/json",
1188
+ Authorization: `Bearer ${apiKey}`
1189
+ },
1190
+ body: JSON.stringify({
1191
+ model,
1192
+ messages: mapClineMessages(request.messages),
1193
+ temperature: request.temperature,
1194
+ stream: true
1195
+ })
1196
+ });
1197
+ if (!response.ok || !response.body) {
1198
+ const errorText = await response.text().catch(() => "");
1199
+ const suffix = extractClineRetrySuffix(response);
1200
+ throw new DomainError(
1201
+ `Cline streaming error HTTP ${response.status}: ${errorText}${suffix}`,
1202
+ response.status === 429 ? ErrorCode.MODEL_RATE_LIMIT : ErrorCode.MODEL_PROVIDER_ERROR,
1203
+ response.status
1204
+ );
1205
+ }
1206
+ const reader = response.body.getReader();
1207
+ const decoder = new TextDecoder();
1208
+ let buffer = "";
1209
+ try {
1210
+ while (true) {
1211
+ const { done, value } = await reader.read();
1212
+ if (done) break;
1213
+ buffer += decoder.decode(value, { stream: true });
1214
+ const lines = buffer.split("\n");
1215
+ buffer = lines.pop() ?? "";
1216
+ for (const line of lines) {
1217
+ const trimmed = line.trim();
1218
+ if (!trimmed || !trimmed.startsWith("data:")) continue;
1219
+ const payload = trimmed.slice(5).trim();
1220
+ if (payload === "[DONE]") break;
1221
+ try {
1222
+ const parsed = JSON.parse(payload);
1223
+ const delta = parsed.choices?.[0]?.delta?.content ?? "";
1224
+ if (delta) {
1225
+ yield { delta };
1226
+ }
1227
+ } catch {
1228
+ }
1229
+ }
1230
+ }
1231
+ } finally {
1232
+ reader.releaseLock();
1233
+ }
1234
+ }
1235
+ };
1236
+ var logger7 = loggerWithConfig(new Logger("FallbackCascade"));
1042
1237
  var FallbackCascade = class {
1043
1238
  name = "fallback-cascade";
1044
1239
  providers;
@@ -1067,7 +1262,7 @@ var FallbackCascade = class {
1067
1262
  const errors = [];
1068
1263
  for (const provider of this.providers) {
1069
1264
  try {
1070
- logger6.debug(
1265
+ logger7.debug(
1071
1266
  `[complete] Attempting provider '${provider.name}' in FallbackCascade`
1072
1267
  );
1073
1268
  const response = await provider.complete(request);
@@ -1075,7 +1270,7 @@ var FallbackCascade = class {
1075
1270
  } catch (err) {
1076
1271
  const errorMsg = err instanceof Error ? err.message : String(err);
1077
1272
  errors.push({ provider: provider.name, error: errorMsg });
1078
- logger6.warn(
1273
+ logger7.warn(
1079
1274
  `[complete] Provider '${provider.name}' failed in FallbackCascade, cascading to next candidate`,
1080
1275
  {
1081
1276
  provider: provider.name,
@@ -1084,7 +1279,7 @@ var FallbackCascade = class {
1084
1279
  );
1085
1280
  }
1086
1281
  }
1087
- logger6.error("[complete] All providers in FallbackCascade exhausted", {
1282
+ logger7.error("[complete] All providers in FallbackCascade exhausted", {
1088
1283
  errors
1089
1284
  });
1090
1285
  throw new DomainError(
@@ -1108,7 +1303,7 @@ var FallbackCascade = class {
1108
1303
  return;
1109
1304
  } catch (err) {
1110
1305
  lastError = err;
1111
- logger6.warn(
1306
+ logger7.warn(
1112
1307
  `[stream] Provider '${provider.name}' failed streaming, attempting next provider in cascade`
1113
1308
  );
1114
1309
  }
@@ -1116,7 +1311,7 @@ var FallbackCascade = class {
1116
1311
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
1117
1312
  }
1118
1313
  };
1119
- var logger7 = loggerWithConfig(new Logger("StructuredOutput"));
1314
+ var logger8 = loggerWithConfig(new Logger("StructuredOutput"));
1120
1315
  function cleanJsonText(raw) {
1121
1316
  const match = /```(?:json)?\s*([\s\S]*?)\s*```/i.exec(raw);
1122
1317
  if (match && match[1]) {
@@ -1145,7 +1340,7 @@ async function extractStructuredOutput(options) {
1145
1340
  return schema.parse(parsedJson);
1146
1341
  } catch (parseOrValidationError) {
1147
1342
  const errorDetail = parseOrValidationError instanceof Error ? parseOrValidationError.message : String(parseOrValidationError);
1148
- logger7.warn(
1343
+ logger8.warn(
1149
1344
  `[extractStructuredOutput] Structured output parsing failed (attempt ${attempts}/${maxRepairRetries + 1})`,
1150
1345
  {
1151
1346
  error: errorDetail
@@ -1177,9 +1372,9 @@ async function extractStructuredOutput(options) {
1177
1372
  422
1178
1373
  );
1179
1374
  }
1180
- var logger8 = loggerWithConfig(new Logger("ProviderFactory"));
1375
+ var logger9 = loggerWithConfig(new Logger("ProviderFactory"));
1181
1376
  function createProvider(type, config = {}) {
1182
- logger8.debug(`[createProvider] Creating LLM provider instance: ${type}`);
1377
+ logger9.debug(`[createProvider] Creating LLM provider instance: ${type}`);
1183
1378
  switch (type) {
1184
1379
  case "ollama":
1185
1380
  return new OllamaAdapter(config);
@@ -1191,6 +1386,8 @@ function createProvider(type, config = {}) {
1191
1386
  return new OpenAIAdapter(config);
1192
1387
  case "anthropic":
1193
1388
  return new AnthropicAdapter(config);
1389
+ case "cline":
1390
+ return new ClineAdapter(config);
1194
1391
  case "cascade": {
1195
1392
  const providers = config.providers ?? createCascadeCandidates();
1196
1393
  return new FallbackCascade({ providers });
@@ -1220,6 +1417,9 @@ function createCascadeCandidates(config = {}) {
1220
1417
  if (config.anthropic) {
1221
1418
  candidates.push(new AnthropicAdapter(config.anthropic));
1222
1419
  }
1420
+ if (config.cline) {
1421
+ candidates.push(new ClineAdapter(config.cline));
1422
+ }
1223
1423
  if (candidates.length === 0) {
1224
1424
  candidates.push(new OllamaAdapter(config.ollama ?? {}));
1225
1425
  }
@@ -1227,7 +1427,7 @@ function createCascadeCandidates(config = {}) {
1227
1427
  }
1228
1428
  function createDefaultProvider(options = {}) {
1229
1429
  if (options.provider) {
1230
- logger8.info(
1430
+ logger9.info(
1231
1431
  `[createDefaultProvider] Using explicitly configured provider: ${options.provider}`
1232
1432
  );
1233
1433
  return createProvider(options.provider, options.config);
@@ -1237,6 +1437,6 @@ function createDefaultProvider(options = {}) {
1237
1437
  });
1238
1438
  }
1239
1439
 
1240
- export { AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, FallbackCascade, FinishReason, GoogleAdapter, GroqAdapter, LLMRequestOptionsSchema, LLMRequestSchema, LLMResponseSchema, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, OpenAIAdapter, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractStructuredOutput, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials };
1440
+ export { AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, ClineAdapter, FallbackCascade, FinishReason, GoogleAdapter, GroqAdapter, LLMRequestOptionsSchema, LLMRequestSchema, LLMResponseSchema, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, OpenAIAdapter, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractClineRetrySuffix, extractClineToolCalls, extractStructuredOutput, mapClineFinishReason, mapClineMessages, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials, restoreClineToolName, sanitizeClineToolName };
1241
1441
  //# sourceMappingURL=index.js.map
1242
1442
  //# sourceMappingURL=index.js.map