@yourgpt/llm-sdk 2.1.4-alpha.0 → 2.1.4-alpha.2

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.
@@ -1,346 +1,4 @@
1
- import { z } from 'zod';
2
-
3
- /**
4
- * Core Types for @yourgpt/llm-sdk
5
- *
6
- * Modern, instance-based types following Vercel AI SDK patterns.
7
- */
8
-
9
- /**
10
- * A language model instance that can generate text.
11
- * This is what provider functions like `openai('gpt-4o')` return.
12
- */
13
- interface LanguageModel {
14
- /** Provider identifier (e.g., 'openai', 'anthropic') */
15
- readonly provider: string;
16
- /** Model identifier (e.g., 'gpt-4o', 'claude-3-5-sonnet') */
17
- readonly modelId: string;
18
- /** Model capabilities for feature detection */
19
- readonly capabilities: ModelCapabilities;
20
- /**
21
- * Generate a complete response (non-streaming)
22
- * Used internally by generateText()
23
- */
24
- doGenerate(params: DoGenerateParams): Promise<DoGenerateResult>;
25
- /**
26
- * Stream a response
27
- * Used internally by streamText()
28
- */
29
- doStream(params: DoGenerateParams): AsyncGenerator<StreamChunk>;
30
- }
31
- /**
32
- * Model capabilities for UI feature flags
33
- */
34
- interface ModelCapabilities {
35
- /** Supports image inputs */
36
- supportsVision: boolean;
37
- /** Supports tool/function calling */
38
- supportsTools: boolean;
39
- /** Supports streaming responses */
40
- supportsStreaming: boolean;
41
- /** Supports JSON mode / structured output */
42
- supportsJsonMode: boolean;
43
- /** Supports extended thinking (Claude) */
44
- supportsThinking: boolean;
45
- /** Supports PDF document inputs */
46
- supportsPDF: boolean;
47
- /** Maximum context tokens */
48
- maxTokens: number;
49
- /** Supported image MIME types */
50
- supportedImageTypes: string[];
51
- }
52
- /**
53
- * Default capabilities for unknown models
54
- */
55
- declare const DEFAULT_CAPABILITIES: ModelCapabilities;
56
- /**
57
- * Core message types for LLM conversations
58
- */
59
- type CoreMessage = SystemMessage | UserMessage | AssistantMessage | ToolMessage;
60
- interface SystemMessage {
61
- role: "system";
62
- content: string;
63
- }
64
- interface UserMessage {
65
- role: "user";
66
- content: string | UserContentPart[];
67
- }
68
- interface AssistantMessage {
69
- role: "assistant";
70
- content: string | null;
71
- toolCalls?: ToolCall$1[];
72
- }
73
- interface ToolMessage {
74
- role: "tool";
75
- toolCallId: string;
76
- content: string;
77
- }
78
- /**
79
- * Content parts for multimodal user messages
80
- */
81
- type UserContentPart = TextPart | ImagePart | FilePart;
82
- interface TextPart {
83
- type: "text";
84
- text: string;
85
- }
86
- interface ImagePart {
87
- type: "image";
88
- /** Base64 data or URL */
89
- image: string | Uint8Array;
90
- /** MIME type (e.g., 'image/png') */
91
- mimeType?: string;
92
- }
93
- interface FilePart {
94
- type: "file";
95
- /** Base64 data or URL */
96
- data: string;
97
- /** MIME type (e.g., 'application/pdf') */
98
- mimeType: string;
99
- }
100
- /**
101
- * Tool definition with Zod schema support
102
- */
103
- interface Tool<TParams = unknown, TResult = unknown> {
104
- /** Tool description for the LLM */
105
- description: string;
106
- /** Zod schema for parameters */
107
- parameters: z.ZodType<TParams>;
108
- /** Execute function */
109
- execute: (params: TParams, context: ToolContext$1) => Promise<TResult>;
110
- /**
111
- * Hide this tool's execution from the chat UI.
112
- * When true, tool calls and results won't be displayed to the user,
113
- * but the tool will still execute normally.
114
- * @default false
115
- */
116
- hidden?: boolean;
117
- }
118
- /**
119
- * Context passed to tool execute function
120
- */
121
- interface ToolContext$1 {
122
- /** Abort signal for cancellation */
123
- abortSignal?: AbortSignal;
124
- /** Unique tool call ID */
125
- toolCallId: string;
126
- /** Optional: messages in conversation */
127
- messages?: CoreMessage[];
128
- }
129
- /**
130
- * Tool call from LLM response
131
- */
132
- interface ToolCall$1 {
133
- /** Unique ID for this tool call */
134
- id: string;
135
- /** Tool name */
136
- name: string;
137
- /** Parsed arguments */
138
- args: Record<string, unknown>;
139
- }
140
- /**
141
- * Tool execution result
142
- */
143
- interface ToolResult {
144
- /** Tool call ID this result corresponds to */
145
- toolCallId: string;
146
- /** Result data (will be JSON stringified for LLM) */
147
- result: unknown;
148
- }
149
- /**
150
- * Parameters for model.doGenerate() and model.doStream()
151
- */
152
- interface DoGenerateParams {
153
- /** Messages to send to LLM */
154
- messages: CoreMessage[];
155
- /** Tools available to the LLM (already formatted for provider) */
156
- tools?: unknown[];
157
- /** Temperature (0-2) */
158
- temperature?: number;
159
- /** Maximum tokens to generate */
160
- maxTokens?: number;
161
- /** Abort signal */
162
- signal?: AbortSignal;
163
- }
164
- /**
165
- * Result from model.doGenerate()
166
- */
167
- interface DoGenerateResult {
168
- /** Generated text content */
169
- text: string;
170
- /** Tool calls requested by the LLM */
171
- toolCalls: ToolCall$1[];
172
- /** Why generation stopped */
173
- finishReason: FinishReason;
174
- /** Token usage */
175
- usage: TokenUsage;
176
- /** Raw provider response (for debugging) */
177
- rawResponse?: unknown;
178
- }
179
- /**
180
- * Finish reason for generation
181
- */
182
- type FinishReason = "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown";
183
- /**
184
- * Token usage statistics
185
- */
186
- interface TokenUsage {
187
- promptTokens: number;
188
- completionTokens: number;
189
- totalTokens: number;
190
- }
191
- /**
192
- * Stream chunk from model.doStream()
193
- */
194
- type StreamChunk = TextDeltaChunk | ToolCallChunk | ToolResultChunk | FinishChunk | ErrorChunk;
195
- interface TextDeltaChunk {
196
- type: "text-delta";
197
- text: string;
198
- }
199
- interface ToolCallChunk {
200
- type: "tool-call";
201
- toolCall: ToolCall$1;
202
- }
203
- interface ToolResultChunk {
204
- type: "tool-result";
205
- toolCallId: string;
206
- result: unknown;
207
- }
208
- interface FinishChunk {
209
- type: "finish";
210
- finishReason: FinishReason;
211
- usage?: TokenUsage;
212
- }
213
- interface ErrorChunk {
214
- type: "error";
215
- error: Error;
216
- }
217
- /**
218
- * Parameters for generateText()
219
- */
220
- interface GenerateTextParams {
221
- /** Language model to use */
222
- model: LanguageModel;
223
- /** Simple prompt (converted to user message) */
224
- prompt?: string;
225
- /** System prompt */
226
- system?: string;
227
- /** Full message history */
228
- messages?: CoreMessage[];
229
- /** Tools available to the LLM */
230
- tools?: Record<string, Tool>;
231
- /** Maximum agentic steps (tool call loops) */
232
- maxSteps?: number;
233
- /** Temperature (0-2) */
234
- temperature?: number;
235
- /** Maximum tokens to generate */
236
- maxTokens?: number;
237
- /** Abort signal */
238
- signal?: AbortSignal;
239
- }
240
- /**
241
- * Result from generateText()
242
- */
243
- interface GenerateTextResult {
244
- /** Final text output */
245
- text: string;
246
- /** Token usage */
247
- usage: TokenUsage;
248
- /** Why generation stopped */
249
- finishReason: FinishReason;
250
- /** All steps taken (for agentic workflows) */
251
- steps: GenerateStep[];
252
- /** All tool calls made across all steps */
253
- toolCalls: ToolCall$1[];
254
- /** All tool results across all steps */
255
- toolResults: ToolResult[];
256
- /** Final message list including tool interactions */
257
- response: {
258
- messages: CoreMessage[];
259
- };
260
- }
261
- /**
262
- * A single step in the generation process
263
- */
264
- interface GenerateStep {
265
- /** Text generated in this step */
266
- text: string;
267
- /** Tool calls made in this step */
268
- toolCalls: ToolCall$1[];
269
- /** Tool results from this step */
270
- toolResults: ToolResult[];
271
- /** Finish reason for this step */
272
- finishReason: FinishReason;
273
- /** Token usage for this step */
274
- usage: TokenUsage;
275
- }
276
- /**
277
- * Parameters for streamText() - same as generateText
278
- */
279
- type StreamTextParams = GenerateTextParams;
280
- /**
281
- * Result from streamText()
282
- */
283
- interface StreamTextResult {
284
- /** Async iterable of text chunks only */
285
- textStream: AsyncIterable<string>;
286
- /** Async iterable of all stream parts */
287
- fullStream: AsyncIterable<StreamPart>;
288
- /** Promise that resolves to full text when complete */
289
- readonly text: Promise<string>;
290
- /** Promise that resolves to usage when complete */
291
- readonly usage: Promise<TokenUsage>;
292
- /** Promise that resolves to finish reason when complete */
293
- readonly finishReason: Promise<FinishReason>;
294
- /** Convert to plain text streaming Response */
295
- toTextStreamResponse(options?: ResponseOptions): Response;
296
- /** Convert to data stream Response (SSE with tool calls) */
297
- toDataStreamResponse(options?: ResponseOptions): Response;
298
- }
299
- /**
300
- * Stream part for fullStream
301
- */
302
- type StreamPart = {
303
- type: "text-delta";
304
- text: string;
305
- } | {
306
- type: "tool-call-start";
307
- toolCallId: string;
308
- toolName: string;
309
- } | {
310
- type: "tool-call-delta";
311
- toolCallId: string;
312
- argsText: string;
313
- } | {
314
- type: "tool-call-complete";
315
- toolCall: ToolCall$1;
316
- } | {
317
- type: "tool-result";
318
- toolCallId: string;
319
- result: unknown;
320
- } | {
321
- type: "step-start";
322
- step: number;
323
- } | {
324
- type: "step-finish";
325
- step: number;
326
- finishReason: FinishReason;
327
- } | {
328
- type: "finish";
329
- finishReason: FinishReason;
330
- usage: TokenUsage;
331
- } | {
332
- type: "error";
333
- error: Error;
334
- };
335
- /**
336
- * Options for Response helpers
337
- */
338
- interface ResponseOptions {
339
- /** Additional headers */
340
- headers?: Record<string, string>;
341
- /** Response status (default: 200) */
342
- status?: number;
343
- }
1
+ import { t as TokenUsage } from './types-CR8mi9I0.js';
344
2
 
345
3
  /**
346
4
  * Stream event types for llm-sdk
@@ -547,6 +205,8 @@ interface DoneEvent extends BaseEvent {
547
205
  messages?: DoneEventMessage[];
548
206
  /** Token usage (server-side only, stripped before sending to client) */
549
207
  usage?: TokenUsageRaw;
208
+ /** Session ID — present when storage adapter created a session for this request */
209
+ threadId?: string;
550
210
  }
551
211
  /**
552
212
  * Union of all stream events
@@ -1457,4 +1117,4 @@ interface OllamaProviderConfig extends BaseProviderConfig {
1457
1117
  options?: OllamaModelOptions;
1458
1118
  }
1459
1119
 
1460
- export { type GoogleProviderConfig as $, type AIProvider as A, type ToolResultChunk as B, type CoreMessage as C, type DoneEventMessage as D, type FinishChunk as E, type FilePart as F, type GenerateTextParams as G, type ErrorChunk as H, type ImagePart as I, type TokenUsage as J, type KnowledgeBaseConfig as K, type LLMAdapter as L, type Message as M, type FinishReason as N, DEFAULT_CAPABILITIES as O, type ProviderToolRuntimeOptions as P, type ChatCompletionRequest as Q, type ResponseOptions as R, type StreamTextParams as S, type ToolContext$1 as T, type UserMessage as U, type AdapterFactory as V, type WebSearchConfig as W, type ProviderCapabilities as X, type BaseProviderConfig as Y, type OpenAIProviderConfig as Z, type AnthropicProviderConfig as _, type GenerateTextResult as a, type XAIProviderConfig as a0, type AzureProviderConfig as a1, type OllamaProviderConfig as a2, type OllamaModelOptions as a3, type ProviderFormatter as a4, type AnthropicTool as a5, type AnthropicToolUse as a6, type AnthropicToolResult as a7, type OpenAITool as a8, type OpenAIToolCall as a9, attachmentToOpenAIImage as aA, type AnthropicContentBlock as aB, type OpenAIContentBlock as aC, type OpenAIToolResult as aa, type GeminiFunctionDeclaration as ab, type GeminiFunctionCall as ac, type GeminiFunctionResponse as ad, type LLMConfig as ae, type ToolLocation as af, type UnifiedToolCall as ag, type UnifiedToolResult as ah, type ToolExecution as ai, type OpenAIToolSelectionHints as aj, type AnthropicToolSelectionHints as ak, type ToolNativeProviderHints as al, type OpenAIProviderToolOptions as am, type AnthropicProviderToolOptions as an, type Citation as ao, type CompletionResult as ap, formatMessages as aq, formatTools as ar, formatMessagesForAnthropic as as, formatMessagesForOpenAI as at, messageToAnthropicContent as au, messageToOpenAIContent as av, hasImageAttachments as aw, hasMediaAttachments as ax, attachmentToAnthropicImage as ay, attachmentToAnthropicDocument as az, type StreamTextResult as b, type Tool as c, type ActionDefinition as d, type ToolDefinition as e, type ToolProfile as f, type StreamEvent as g, type ToolCallInfo as h, type TokenUsageRaw as i, type ToolResponse as j, type LanguageModel as k, type ModelCapabilities as l, type DoGenerateParams as m, type DoGenerateResult as n, type SystemMessage as o, type AssistantMessage as p, type ToolMessage as q, type UserContentPart as r, type TextPart as s, type ToolCall$1 as t, type ToolResult as u, type GenerateStep as v, type StreamPart as w, type StreamChunk as x, type TextDeltaChunk as y, type ToolCallChunk as z };
1120
+ export { hasImageAttachments as $, type AIProvider as A, type BaseProviderConfig as B, type ChatCompletionRequest as C, type DoneEventMessage as D, type AnthropicToolSelectionHints as E, type ToolNativeProviderHints as F, type GoogleProviderConfig as G, type OpenAIProviderToolOptions as H, type AnthropicProviderToolOptions as I, type Citation as J, type KnowledgeBaseConfig as K, type LLMAdapter as L, type Message as M, type CompletionResult as N, type OpenAIProviderConfig as O, type ProviderToolRuntimeOptions as P, formatMessages as Q, formatTools as R, type StreamEvent as S, type ToolDefinition as T, type UnifiedToolCall as U, formatMessagesForAnthropic as V, type WebSearchConfig as W, type XAIProviderConfig as X, formatMessagesForOpenAI as Y, messageToAnthropicContent as Z, messageToOpenAIContent as _, type ActionDefinition as a, hasMediaAttachments as a0, attachmentToAnthropicImage as a1, attachmentToAnthropicDocument as a2, attachmentToOpenAIImage as a3, type AnthropicContentBlock as a4, type OpenAIContentBlock as a5, type ToolProfile as b, type ToolCallInfo as c, type TokenUsageRaw as d, type ToolResponse as e, type AdapterFactory as f, type ProviderCapabilities as g, type AnthropicProviderConfig as h, type AzureProviderConfig as i, type OllamaProviderConfig as j, type OllamaModelOptions as k, type ProviderFormatter as l, type AnthropicTool as m, type AnthropicToolUse as n, type AnthropicToolResult as o, type OpenAITool as p, type OpenAIToolCall as q, type OpenAIToolResult as r, type GeminiFunctionDeclaration as s, type GeminiFunctionCall as t, type GeminiFunctionResponse as u, type LLMConfig as v, type ToolLocation as w, type UnifiedToolResult as x, type ToolExecution as y, type OpenAIToolSelectionHints as z };
@@ -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