@yourgpt/llm-sdk 2.1.4-alpha.1 → 2.1.4-alpha.3

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.
Files changed (57) hide show
  1. package/dist/adapters/index.d.mts +4 -2
  2. package/dist/adapters/index.d.ts +4 -2
  3. package/dist/base-5n-UuPfS.d.mts +768 -0
  4. package/dist/base-Di31iy_8.d.ts +768 -0
  5. package/dist/fallback/index.d.mts +96 -0
  6. package/dist/fallback/index.d.ts +96 -0
  7. package/dist/fallback/index.js +284 -0
  8. package/dist/fallback/index.mjs +280 -0
  9. package/dist/index.d.mts +62 -3
  10. package/dist/index.d.ts +62 -3
  11. package/dist/index.js +117 -2
  12. package/dist/index.mjs +116 -3
  13. package/dist/providers/anthropic/index.d.mts +3 -1
  14. package/dist/providers/anthropic/index.d.ts +3 -1
  15. package/dist/providers/azure/index.d.mts +3 -1
  16. package/dist/providers/azure/index.d.ts +3 -1
  17. package/dist/providers/google/index.d.mts +3 -1
  18. package/dist/providers/google/index.d.ts +3 -1
  19. package/dist/providers/ollama/index.d.mts +4 -2
  20. package/dist/providers/ollama/index.d.ts +4 -2
  21. package/dist/providers/openai/index.d.mts +3 -1
  22. package/dist/providers/openai/index.d.ts +3 -1
  23. package/dist/providers/openrouter/index.d.mts +3 -1
  24. package/dist/providers/openrouter/index.d.ts +3 -1
  25. package/dist/providers/xai/index.d.mts +3 -1
  26. package/dist/providers/xai/index.d.ts +3 -1
  27. package/dist/types-BQl1suAv.d.mts +212 -0
  28. package/dist/types-C0vLXzuw.d.ts +355 -0
  29. package/dist/types-CNL8ZRne.d.ts +212 -0
  30. package/dist/types-CR8mi9I0.d.mts +417 -0
  31. package/dist/types-CR8mi9I0.d.ts +417 -0
  32. package/dist/types-VDgiUvH2.d.mts +355 -0
  33. package/dist/yourgpt/index.d.mts +77 -0
  34. package/dist/yourgpt/index.d.ts +77 -0
  35. package/dist/yourgpt/index.js +167 -0
  36. package/dist/yourgpt/index.mjs +164 -0
  37. package/package.json +12 -1
  38. package/dist/adapters/index.js.map +0 -1
  39. package/dist/adapters/index.mjs.map +0 -1
  40. package/dist/index.js.map +0 -1
  41. package/dist/index.mjs.map +0 -1
  42. package/dist/providers/anthropic/index.js.map +0 -1
  43. package/dist/providers/anthropic/index.mjs.map +0 -1
  44. package/dist/providers/azure/index.js.map +0 -1
  45. package/dist/providers/azure/index.mjs.map +0 -1
  46. package/dist/providers/google/index.js.map +0 -1
  47. package/dist/providers/google/index.mjs.map +0 -1
  48. package/dist/providers/ollama/index.js.map +0 -1
  49. package/dist/providers/ollama/index.mjs.map +0 -1
  50. package/dist/providers/openai/index.js.map +0 -1
  51. package/dist/providers/openai/index.mjs.map +0 -1
  52. package/dist/providers/openrouter/index.js.map +0 -1
  53. package/dist/providers/openrouter/index.mjs.map +0 -1
  54. package/dist/providers/xai/index.js.map +0 -1
  55. package/dist/providers/xai/index.mjs.map +0 -1
  56. package/dist/types-COAOEe_y.d.mts +0 -1460
  57. package/dist/types-COAOEe_y.d.ts +0 -1460
@@ -0,0 +1,355 @@
1
+ import { L as LLMAdapter, T as ToolDefinition, U as UnifiedToolCall, h as UnifiedToolResult } from './base-5n-UuPfS.mjs';
2
+
3
+ /**
4
+ * Provider Types
5
+ *
6
+ * Defines interfaces for:
7
+ * 1. Provider Formatters (for tool transformations in agent loop)
8
+ * 2. Multi-provider architecture (AIProvider, capabilities, configs)
9
+ */
10
+
11
+ /**
12
+ * Provider formatter interface
13
+ *
14
+ * Each provider implements this interface to handle:
15
+ * - Tool definition transformation
16
+ * - Tool call parsing from responses
17
+ * - Tool result formatting
18
+ * - Stop reason detection
19
+ */
20
+ interface ProviderFormatter {
21
+ /**
22
+ * Transform unified tool definitions to provider format
23
+ */
24
+ transformTools(tools: ToolDefinition[]): unknown[];
25
+ /**
26
+ * Parse tool calls from provider response
27
+ */
28
+ parseToolCalls(response: unknown): UnifiedToolCall[];
29
+ /**
30
+ * Format tool results for provider
31
+ */
32
+ formatToolResults(results: UnifiedToolResult[]): unknown[];
33
+ /**
34
+ * Check if response indicates tool use is requested
35
+ */
36
+ isToolUseStop(response: unknown): boolean;
37
+ /**
38
+ * Check if response indicates end of turn
39
+ */
40
+ isEndTurnStop(response: unknown): boolean;
41
+ /**
42
+ * Get stop reason string from response
43
+ */
44
+ getStopReason(response: unknown): string;
45
+ /**
46
+ * Extract text content from response
47
+ */
48
+ extractTextContent(response: unknown): string;
49
+ /**
50
+ * Build assistant message with tool calls for conversation history
51
+ */
52
+ buildAssistantToolMessage(toolCalls: UnifiedToolCall[], textContent?: string): unknown;
53
+ /**
54
+ * Build user message with tool results for conversation history
55
+ */
56
+ buildToolResultMessage(results: UnifiedToolResult[]): unknown;
57
+ }
58
+ /**
59
+ * Anthropic tool definition format
60
+ */
61
+ interface AnthropicTool {
62
+ name: string;
63
+ description: string;
64
+ input_schema: {
65
+ type: "object";
66
+ properties: Record<string, unknown>;
67
+ required?: string[];
68
+ };
69
+ }
70
+ /**
71
+ * Anthropic tool_use block from response
72
+ */
73
+ interface AnthropicToolUse {
74
+ type: "tool_use";
75
+ id: string;
76
+ name: string;
77
+ input: Record<string, unknown>;
78
+ }
79
+ /**
80
+ * Anthropic tool_result block
81
+ */
82
+ interface AnthropicToolResult {
83
+ type: "tool_result";
84
+ tool_use_id: string;
85
+ content: string;
86
+ }
87
+ /**
88
+ * OpenAI tool definition format
89
+ */
90
+ interface OpenAITool {
91
+ type: "function";
92
+ function: {
93
+ name: string;
94
+ description: string;
95
+ parameters: {
96
+ type: "object";
97
+ properties: Record<string, unknown>;
98
+ required?: string[];
99
+ };
100
+ };
101
+ }
102
+ /**
103
+ * OpenAI tool call from response
104
+ */
105
+ interface OpenAIToolCall {
106
+ id: string;
107
+ type: "function";
108
+ function: {
109
+ name: string;
110
+ arguments: string;
111
+ };
112
+ }
113
+ /**
114
+ * OpenAI tool result message
115
+ */
116
+ interface OpenAIToolResult {
117
+ role: "tool";
118
+ tool_call_id: string;
119
+ content: string;
120
+ }
121
+ /**
122
+ * Google Gemini function declaration
123
+ */
124
+ interface GeminiFunctionDeclaration {
125
+ name: string;
126
+ description: string;
127
+ parameters?: {
128
+ type: "object";
129
+ properties: Record<string, unknown>;
130
+ required?: string[];
131
+ };
132
+ }
133
+ /**
134
+ * Gemini function call from response
135
+ */
136
+ interface GeminiFunctionCall {
137
+ name: string;
138
+ args: Record<string, unknown>;
139
+ }
140
+ /**
141
+ * Gemini function response
142
+ */
143
+ interface GeminiFunctionResponse {
144
+ name: string;
145
+ response: Record<string, unknown>;
146
+ }
147
+ /**
148
+ * Capabilities of a model for UI feature flags
149
+ * UI components can use this to enable/disable features
150
+ */
151
+ interface ProviderCapabilities {
152
+ /** Supports image inputs */
153
+ supportsVision: boolean;
154
+ /** Supports tool/function calling */
155
+ supportsTools: boolean;
156
+ /** Supports extended thinking (Claude, DeepSeek) */
157
+ supportsThinking: boolean;
158
+ /** Supports streaming responses */
159
+ supportsStreaming: boolean;
160
+ /** Supports PDF document inputs */
161
+ supportsPDF: boolean;
162
+ /** Supports audio inputs */
163
+ supportsAudio: boolean;
164
+ /** Supports video inputs */
165
+ supportsVideo: boolean;
166
+ /** Maximum context tokens */
167
+ maxTokens: number;
168
+ /** Supported image MIME types */
169
+ supportedImageTypes: string[];
170
+ /** Supported audio MIME types */
171
+ supportedAudioTypes?: string[];
172
+ /** Supported video MIME types */
173
+ supportedVideoTypes?: string[];
174
+ /** Supports JSON mode / structured output */
175
+ supportsJsonMode?: boolean;
176
+ /** Supports system messages */
177
+ supportsSystemMessages?: boolean;
178
+ }
179
+ /**
180
+ * AI Provider interface (object form)
181
+ *
182
+ * Wraps existing LLMAdapter with additional metadata:
183
+ * - Supported models list
184
+ * - Per-model capabilities
185
+ * - Provider name
186
+ */
187
+ interface AIProviderObject {
188
+ /** Provider name (e.g., 'openai', 'anthropic') */
189
+ readonly name: string;
190
+ /** List of supported model IDs */
191
+ readonly supportedModels: string[];
192
+ /**
193
+ * Get a language model adapter for the given model ID
194
+ * Returns the existing LLMAdapter interface - no breaking changes
195
+ */
196
+ languageModel(modelId: string): LLMAdapter;
197
+ /**
198
+ * Get capabilities for a specific model
199
+ * UI components use this to enable/disable features
200
+ */
201
+ getCapabilities(modelId: string): ProviderCapabilities;
202
+ /**
203
+ * Optional: Get an embedding model (future expansion)
204
+ */
205
+ embeddingModel?(modelId: string): EmbeddingModel;
206
+ }
207
+ /**
208
+ * Callable AI Provider (Vercel AI SDK style)
209
+ *
210
+ * A function that returns a LanguageModel when called with a model ID,
211
+ * but also has properties for provider metadata and methods.
212
+ *
213
+ * @example
214
+ * ```typescript
215
+ * const openai = createOpenAI({ apiKey: '...' });
216
+ *
217
+ * // Callable - returns LanguageModel directly (Vercel AI SDK style)
218
+ * const model = openai('gpt-4o');
219
+ *
220
+ * // Also supports method calls (backward compatible)
221
+ * const model2 = openai.languageModel('gpt-4o');
222
+ *
223
+ * // Check capabilities
224
+ * const caps = openai.getCapabilities('gpt-4o');
225
+ * if (caps.supportsVision) {
226
+ * // Show image upload button
227
+ * }
228
+ * ```
229
+ */
230
+ interface AIProvider extends AIProviderObject {
231
+ /**
232
+ * Call the provider directly with a model ID to get a LanguageModel
233
+ * This is the Vercel AI SDK style pattern
234
+ */
235
+ (modelId: string): LLMAdapter;
236
+ }
237
+ /**
238
+ * Embedding model interface (for future expansion)
239
+ */
240
+ interface EmbeddingModel {
241
+ readonly provider: string;
242
+ readonly modelId: string;
243
+ embed(texts: string[]): Promise<number[][]>;
244
+ }
245
+ /**
246
+ * Base provider configuration
247
+ */
248
+ interface BaseProviderConfig {
249
+ /** API key (falls back to environment variable) */
250
+ apiKey?: string;
251
+ /** Custom base URL */
252
+ baseUrl?: string;
253
+ /** Request timeout in milliseconds */
254
+ timeout?: number;
255
+ /** Custom headers to include */
256
+ headers?: Record<string, string>;
257
+ }
258
+ /**
259
+ * OpenAI provider configuration
260
+ */
261
+ interface OpenAIProviderConfig extends BaseProviderConfig {
262
+ /** OpenAI organization ID */
263
+ organization?: string;
264
+ /** OpenAI project ID */
265
+ project?: string;
266
+ /** Vision detail level for images */
267
+ imageDetail?: "auto" | "low" | "high";
268
+ }
269
+ /**
270
+ * Anthropic provider configuration
271
+ */
272
+ interface AnthropicProviderConfig extends BaseProviderConfig {
273
+ /** Extended thinking budget in tokens (minimum 1024) */
274
+ thinkingBudget?: number;
275
+ /** Enable prompt caching */
276
+ cacheControl?: boolean;
277
+ }
278
+ /**
279
+ * Google provider configuration
280
+ */
281
+ interface GoogleProviderConfig extends BaseProviderConfig {
282
+ /** Safety settings */
283
+ safetySettings?: GoogleSafetySetting[];
284
+ /** Grounding configuration (for web search) */
285
+ groundingConfig?: GoogleGroundingConfig;
286
+ }
287
+ /**
288
+ * Google safety setting
289
+ */
290
+ interface GoogleSafetySetting {
291
+ category: "HARM_CATEGORY_HARASSMENT" | "HARM_CATEGORY_HATE_SPEECH" | "HARM_CATEGORY_SEXUALLY_EXPLICIT" | "HARM_CATEGORY_DANGEROUS_CONTENT";
292
+ threshold: "BLOCK_NONE" | "BLOCK_LOW_AND_ABOVE" | "BLOCK_MEDIUM_AND_ABOVE" | "BLOCK_HIGH_AND_ABOVE";
293
+ }
294
+ /**
295
+ * Google grounding configuration
296
+ */
297
+ interface GoogleGroundingConfig {
298
+ /** Enable Google Search grounding */
299
+ googleSearchRetrieval?: boolean;
300
+ }
301
+ /**
302
+ * xAI provider configuration
303
+ */
304
+ interface XAIProviderConfig extends BaseProviderConfig {
305
+ }
306
+ /**
307
+ * Azure OpenAI provider configuration
308
+ */
309
+ interface AzureProviderConfig extends BaseProviderConfig {
310
+ /** Azure resource name */
311
+ resourceName: string;
312
+ /** Deployment name */
313
+ deploymentName: string;
314
+ /** API version (default: 2024-02-15-preview) */
315
+ apiVersion?: string;
316
+ }
317
+ /**
318
+ * Ollama model-specific options
319
+ * These map to Ollama's native API options
320
+ */
321
+ interface OllamaModelOptions {
322
+ /** Context window size (default varies by model) */
323
+ num_ctx?: number;
324
+ /** Max tokens to predict (-1 = infinite, -2 = fill context) */
325
+ num_predict?: number;
326
+ /** Mirostat sampling (0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0) */
327
+ mirostat?: 0 | 1 | 2;
328
+ /** Mirostat learning rate (default: 0.1) */
329
+ mirostat_eta?: number;
330
+ /** Mirostat target entropy (default: 5.0) */
331
+ mirostat_tau?: number;
332
+ /** Repeat penalty (default: 1.1) */
333
+ repeat_penalty?: number;
334
+ /** Random seed for reproducibility (-1 = random) */
335
+ seed?: number;
336
+ /** Top-k sampling (default: 40) */
337
+ top_k?: number;
338
+ /** Top-p (nucleus) sampling (default: 0.9) */
339
+ top_p?: number;
340
+ /** Min-p sampling (default: 0.0) */
341
+ min_p?: number;
342
+ /** Stop sequences */
343
+ stop?: string[];
344
+ /** Temperature override (also available in config) */
345
+ temperature?: number;
346
+ }
347
+ /**
348
+ * Ollama provider configuration
349
+ */
350
+ interface OllamaProviderConfig extends BaseProviderConfig {
351
+ /** Default Ollama-specific model options */
352
+ options?: OllamaModelOptions;
353
+ }
354
+
355
+ export type { AIProvider as A, BaseProviderConfig as B, GoogleProviderConfig as G, OpenAIProviderConfig as O, ProviderCapabilities as P, XAIProviderConfig as X, AnthropicProviderConfig as a, AzureProviderConfig as b, OllamaProviderConfig as c, OllamaModelOptions as d, ProviderFormatter as e, AnthropicTool as f, AnthropicToolUse as g, AnthropicToolResult as h, OpenAITool as i, OpenAIToolCall as j, OpenAIToolResult as k, GeminiFunctionDeclaration as l, GeminiFunctionCall as m, GeminiFunctionResponse as n };
@@ -0,0 +1,77 @@
1
+ import { e as StorageMessage, d as StorageAdapter, v as StorageFile } from '../types-CR8mi9I0.mjs';
2
+ import 'zod';
3
+
4
+ /**
5
+ * @yourgpt/llm-sdk/yourgpt
6
+ *
7
+ * YourGPT platform integration — session & message persistence.
8
+ * Implements the generic StorageAdapter interface.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { createRuntime } from '@yourgpt/llm-sdk'
13
+ * import { createYourGPT } from '@yourgpt/llm-sdk/yourgpt'
14
+ *
15
+ * const yourgpt = createYourGPT({ apiKey, widgetUid })
16
+ * const runtime = createRuntime({ provider, model, storage: yourgpt })
17
+ *
18
+ * // That's it — runtime auto-creates sessions and persists messages.
19
+ * app.post('/api/copilot/chat', runtime.expressHandler())
20
+ * ```
21
+ */
22
+
23
+ interface YourGPTConfig {
24
+ /** Your YourGPT API key — server-side only, never expose to browser */
25
+ apiKey: string;
26
+ /** Widget UID — scopes all sessions to this project */
27
+ widgetUid: string;
28
+ /** Override API base URL. Defaults to https://api.yourgpt.ai */
29
+ endpoint?: string;
30
+ /**
31
+ * Error handler — called when any adapter operation fails.
32
+ * Receives the error and the operation name (createSession, saveMessages, uploadFile).
33
+ * If not provided, errors are thrown to the caller.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * onError: (error, operation, params) => {
38
+ * logger.error(`[YourGPT] ${operation} failed:`, error, params);
39
+ * Sentry.captureException(error, { tags: { operation }, extra: params });
40
+ * }
41
+ * ```
42
+ */
43
+ onError?: (error: Error, operation: string, params?: Record<string, unknown>) => void;
44
+ }
45
+ /** @deprecated Use `YourGPTConfig` instead */
46
+ type YourGPTAdapterConfig = YourGPTConfig;
47
+ interface YourGPTSession {
48
+ /** Use this as threadId in subsequent chat requests */
49
+ id: string;
50
+ title?: string;
51
+ createdAt: Date;
52
+ updatedAt: Date;
53
+ }
54
+ /** @deprecated Use `StorageMessage` from `@yourgpt/llm-sdk` instead */
55
+ type NewYourGPTMessage = StorageMessage;
56
+ interface CreateSessionData {
57
+ title?: string;
58
+ metadata?: Record<string, unknown>;
59
+ }
60
+ /**
61
+ * YourGPT platform adapter.
62
+ * Extends StorageAdapter with richer session return type.
63
+ */
64
+ interface YourGPT extends StorageAdapter {
65
+ createSession(data?: CreateSessionData): Promise<YourGPTSession>;
66
+ saveMessages(sessionId: string, messages: StorageMessage[]): Promise<void>;
67
+ uploadFile(file: StorageFile): Promise<{
68
+ url: string;
69
+ }>;
70
+ }
71
+ /** @deprecated Use `YourGPT` instead */
72
+ type YourGPTAdapter = YourGPT;
73
+ declare function createYourGPT(config: YourGPTConfig): YourGPT;
74
+ /** @deprecated Use `createYourGPT` instead */
75
+ declare const createYourGPTAdapter: typeof createYourGPT;
76
+
77
+ export { type CreateSessionData, type NewYourGPTMessage, type YourGPT, type YourGPTAdapter, type YourGPTAdapterConfig, type YourGPTConfig, type YourGPTSession, createYourGPT, createYourGPTAdapter };
@@ -0,0 +1,77 @@
1
+ import { e as StorageMessage, d as StorageAdapter, v as StorageFile } from '../types-CR8mi9I0.js';
2
+ import 'zod';
3
+
4
+ /**
5
+ * @yourgpt/llm-sdk/yourgpt
6
+ *
7
+ * YourGPT platform integration — session & message persistence.
8
+ * Implements the generic StorageAdapter interface.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { createRuntime } from '@yourgpt/llm-sdk'
13
+ * import { createYourGPT } from '@yourgpt/llm-sdk/yourgpt'
14
+ *
15
+ * const yourgpt = createYourGPT({ apiKey, widgetUid })
16
+ * const runtime = createRuntime({ provider, model, storage: yourgpt })
17
+ *
18
+ * // That's it — runtime auto-creates sessions and persists messages.
19
+ * app.post('/api/copilot/chat', runtime.expressHandler())
20
+ * ```
21
+ */
22
+
23
+ interface YourGPTConfig {
24
+ /** Your YourGPT API key — server-side only, never expose to browser */
25
+ apiKey: string;
26
+ /** Widget UID — scopes all sessions to this project */
27
+ widgetUid: string;
28
+ /** Override API base URL. Defaults to https://api.yourgpt.ai */
29
+ endpoint?: string;
30
+ /**
31
+ * Error handler — called when any adapter operation fails.
32
+ * Receives the error and the operation name (createSession, saveMessages, uploadFile).
33
+ * If not provided, errors are thrown to the caller.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * onError: (error, operation, params) => {
38
+ * logger.error(`[YourGPT] ${operation} failed:`, error, params);
39
+ * Sentry.captureException(error, { tags: { operation }, extra: params });
40
+ * }
41
+ * ```
42
+ */
43
+ onError?: (error: Error, operation: string, params?: Record<string, unknown>) => void;
44
+ }
45
+ /** @deprecated Use `YourGPTConfig` instead */
46
+ type YourGPTAdapterConfig = YourGPTConfig;
47
+ interface YourGPTSession {
48
+ /** Use this as threadId in subsequent chat requests */
49
+ id: string;
50
+ title?: string;
51
+ createdAt: Date;
52
+ updatedAt: Date;
53
+ }
54
+ /** @deprecated Use `StorageMessage` from `@yourgpt/llm-sdk` instead */
55
+ type NewYourGPTMessage = StorageMessage;
56
+ interface CreateSessionData {
57
+ title?: string;
58
+ metadata?: Record<string, unknown>;
59
+ }
60
+ /**
61
+ * YourGPT platform adapter.
62
+ * Extends StorageAdapter with richer session return type.
63
+ */
64
+ interface YourGPT extends StorageAdapter {
65
+ createSession(data?: CreateSessionData): Promise<YourGPTSession>;
66
+ saveMessages(sessionId: string, messages: StorageMessage[]): Promise<void>;
67
+ uploadFile(file: StorageFile): Promise<{
68
+ url: string;
69
+ }>;
70
+ }
71
+ /** @deprecated Use `YourGPT` instead */
72
+ type YourGPTAdapter = YourGPT;
73
+ declare function createYourGPT(config: YourGPTConfig): YourGPT;
74
+ /** @deprecated Use `createYourGPT` instead */
75
+ declare const createYourGPTAdapter: typeof createYourGPT;
76
+
77
+ export { type CreateSessionData, type NewYourGPTMessage, type YourGPT, type YourGPTAdapter, type YourGPTAdapterConfig, type YourGPTConfig, type YourGPTSession, createYourGPT, createYourGPTAdapter };
@@ -0,0 +1,167 @@
1
+ 'use strict';
2
+
3
+ // src/yourgpt/index.ts
4
+ function createYourGPT(config) {
5
+ const base = (config.endpoint ?? "https://api.yourgpt.ai").replace(/\/$/, "");
6
+ const headers = {
7
+ "Content-Type": "application/json",
8
+ "api-key": config.apiKey
9
+ };
10
+ const onError = config.onError;
11
+ async function call(path, body = {}) {
12
+ const payload = { widget_uid: config.widgetUid, ...body };
13
+ const res = await fetch(`${base}${path}`, {
14
+ method: "POST",
15
+ headers,
16
+ body: JSON.stringify(payload)
17
+ });
18
+ if (!res.ok) {
19
+ const text = await res.text().catch(() => res.statusText);
20
+ throw new Error(`YourGPT API [${res.status}] ${path}: ${text}`);
21
+ }
22
+ return res.json();
23
+ }
24
+ async function safe(operation, params, fn) {
25
+ try {
26
+ return await fn();
27
+ } catch (err) {
28
+ const error = err instanceof Error ? err : new Error(String(err));
29
+ if (onError) {
30
+ onError(error, operation, params);
31
+ }
32
+ throw error;
33
+ }
34
+ }
35
+ return {
36
+ async createSession(data = {}) {
37
+ return safe("createSession", { title: data.title }, async () => {
38
+ const raw = await call(
39
+ "/chatbot/v1/copilot-sdk/createSession",
40
+ data
41
+ );
42
+ const d = raw.data ?? raw;
43
+ return {
44
+ id: String(d.session_uid ?? d.id),
45
+ title: d.title ?? void 0,
46
+ createdAt: new Date(d.createdAt ?? d.created_at),
47
+ updatedAt: new Date(d.updatedAt ?? d.updated_at)
48
+ };
49
+ });
50
+ },
51
+ async saveMessages(sessionId, messages) {
52
+ return safe(
53
+ "saveMessages",
54
+ {
55
+ sessionId,
56
+ messageCount: messages.length,
57
+ roles: messages.map((m) => m.role)
58
+ },
59
+ async () => {
60
+ const num = Number(sessionId);
61
+ const sessionUid = Number.isSafeInteger(num) ? num : sessionId;
62
+ const toolResults = /* @__PURE__ */ new Map();
63
+ for (const msg of messages) {
64
+ if (msg.role === "tool" && msg.toolCallId) {
65
+ toolResults.set(msg.toolCallId, msg.content ?? "");
66
+ }
67
+ }
68
+ for (const msg of messages) {
69
+ if (msg.role === "tool") {
70
+ continue;
71
+ } else if (msg.role === "assistant" && msg.toolCalls?.length) {
72
+ if (msg.content) {
73
+ await call("/chatbot/v1/copilot-sdk/createMessage", {
74
+ session_uid: sessionUid,
75
+ message: msg.content,
76
+ send_by: "assistant",
77
+ content_type: "text"
78
+ });
79
+ }
80
+ for (const tc of msg.toolCalls) {
81
+ const toolName = tc.function?.name ?? "unknown";
82
+ let toolArgs = {};
83
+ try {
84
+ toolArgs = typeof tc.function?.arguments === "string" ? JSON.parse(tc.function.arguments) : tc.function?.arguments ?? {};
85
+ } catch {
86
+ }
87
+ const response = tc.id ? toolResults.get(tc.id) ?? null : null;
88
+ await call("/chatbot/v1/copilot-sdk/createToolMessage", {
89
+ session_uid: sessionUid,
90
+ skill: "copilot-tool",
91
+ extra_data: {
92
+ tool_name: toolName,
93
+ tool_arguments: toolArgs,
94
+ tool_call_id: tc.id ?? null,
95
+ status: "completed",
96
+ tool_response: response
97
+ }
98
+ });
99
+ }
100
+ } else if (msg.role === "user" || msg.role === "assistant") {
101
+ await call("/chatbot/v1/copilot-sdk/createMessage", {
102
+ session_uid: sessionUid,
103
+ message: msg.content,
104
+ send_by: msg.role === "user" ? "user" : "assistant",
105
+ content_type: msg.contentType || "text",
106
+ ...msg.url ? { url: msg.url } : {}
107
+ });
108
+ }
109
+ }
110
+ }
111
+ );
112
+ },
113
+ async uploadFile(file) {
114
+ return safe(
115
+ "uploadFile",
116
+ {
117
+ filename: file.filename,
118
+ mimeType: file.mimeType,
119
+ dataLength: file.data?.length
120
+ },
121
+ async () => {
122
+ const raw = await call("/chatbot/v1/copilot-sdk/getSignedUrl", {
123
+ file_name: file.filename || `upload_${Date.now()}`
124
+ });
125
+ const signedUrl = raw.data?.upload_url ?? raw.data?.url ?? raw.url;
126
+ const successUrl = raw.data?.file_url ?? raw.data?.success_url ?? raw.success_url;
127
+ if (!signedUrl) {
128
+ throw new Error(
129
+ "uploadFile: no signed URL in response \u2014 " + JSON.stringify(raw)
130
+ );
131
+ }
132
+ let body;
133
+ let rawData = file.data;
134
+ const dataUriMatch = rawData.match(/^data:[^;]+;base64,(.+)$/);
135
+ if (dataUriMatch) rawData = dataUriMatch[1];
136
+ if (typeof Buffer !== "undefined") {
137
+ body = Buffer.from(rawData, "base64");
138
+ } else {
139
+ const binary = atob(rawData);
140
+ const bytes = new Uint8Array(binary.length);
141
+ for (let i = 0; i < binary.length; i++)
142
+ bytes[i] = binary.charCodeAt(i);
143
+ body = new Blob([bytes], { type: file.mimeType });
144
+ }
145
+ const uploadRes = await fetch(signedUrl, {
146
+ method: "PUT",
147
+ headers: { "Content-Type": file.mimeType },
148
+ body
149
+ });
150
+ if (!uploadRes.ok) {
151
+ throw new Error(
152
+ `uploadFile: PUT to signed URL failed with ${uploadRes.status}`
153
+ );
154
+ }
155
+ const finalUrl = successUrl || signedUrl.split("?")[0];
156
+ return { url: finalUrl };
157
+ }
158
+ );
159
+ }
160
+ };
161
+ }
162
+ var createYourGPTAdapter = createYourGPT;
163
+
164
+ exports.createYourGPT = createYourGPT;
165
+ exports.createYourGPTAdapter = createYourGPTAdapter;
166
+ //# sourceMappingURL=index.js.map
167
+ //# sourceMappingURL=index.js.map