@amigo-ai/sdk 0.64.0 → 0.65.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.cjs CHANGED
@@ -550,8 +550,8 @@ var ConversationResource = class {
550
550
  throw new BadRequestError("textMessage is required when request_format is 'text'");
551
551
  }
552
552
  const form = new FormData();
553
- const blob = new Blob([input], { type: "text/plain; charset=utf-8" });
554
- form.append("recorded_message", blob, "message.txt");
553
+ form.append("initial_message_type", "user-message");
554
+ form.append("recorded_message", input);
555
555
  bodyToSend = form;
556
556
  } else if (queryParams.request_format === "voice") {
557
557
  if (typeof input === "string") {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/core/errors.ts", "../src/core/utils.ts", "../src/core/openapi-client.ts", "../src/core/auth.ts", "../src/core/retry.ts", "../src/resources/organization.ts", "../src/resources/conversation.ts", "../src/resources/services.ts", "../src/resources/user.ts"],
4
- "sourcesContent": ["import { ConfigurationError } from './core/errors'\nimport { createAmigoFetch } from './core/openapi-client'\nimport { OrganizationResource } from './resources/organization'\nimport { ConversationResource } from './resources/conversation'\nimport { ServiceResource } from './resources/services'\nimport { UserResource } from './resources/user'\nimport type { RetryOptions } from './core/retry'\n\nexport interface AmigoSdkConfig {\n /** API key from Amigo dashboard */\n apiKey: string\n /** API-key ID from Amigo dashboard */\n apiKeyId: string\n /** User ID on whose behalf the request is made */\n userId: string\n /** The Organization ID */\n orgId: string\n /** Base URL of the Amigo API */\n baseUrl?: string\n /** Retry configuration for HTTP requests */\n retry?: RetryOptions\n}\n\nconst defaultBaseUrl = 'https://api.amigo.ai'\n\nexport class AmigoClient {\n readonly organizations: OrganizationResource\n readonly conversations: ConversationResource\n readonly services: ServiceResource\n readonly users: UserResource\n readonly config: AmigoSdkConfig\n\n constructor(config: AmigoSdkConfig) {\n this.config = validateConfig(config)\n\n const api = createAmigoFetch(this.config)\n this.organizations = new OrganizationResource(api, this.config.orgId)\n this.conversations = new ConversationResource(api, this.config.orgId)\n this.services = new ServiceResource(api, this.config.orgId)\n this.users = new UserResource(api, this.config.orgId)\n }\n}\n\nfunction validateConfig(config: AmigoSdkConfig) {\n if (!config.apiKey) {\n throw new ConfigurationError('API key is required', 'apiKey')\n }\n if (!config.apiKeyId) {\n throw new ConfigurationError('API key ID is required', 'apiKeyId')\n }\n if (!config.userId) {\n throw new ConfigurationError('User ID is required', 'userId')\n }\n if (!config.orgId) {\n throw new ConfigurationError('Organization ID is required', 'orgId')\n }\n if (!config.baseUrl) {\n config.baseUrl = defaultBaseUrl\n }\n return config\n}\n\n// Export all errors as a namespace to avoid polluting the main import space\nexport * as errors from './core/errors'\n\n// Re-export useful types for consumers\nexport type { components, operations, paths } from './generated/api-types'\n", "import type { Middleware } from 'openapi-fetch'\nimport { isNetworkError, parseResponseBody } from './utils'\n\n/**\n * Base error class for all Amigo SDK errors.\n * Provides common functionality and error identification.\n */\nexport class AmigoError extends Error {\n /**\n * Unique error code for programmatic error handling\n */\n readonly errorCode?: string\n\n /**\n * HTTP status code if applicable\n */\n readonly statusCode?: number\n\n /**\n * Additional context data\n */\n context?: Record<string, unknown>\n\n constructor(message: string, options?: Record<string, unknown>) {\n super(message)\n this.name = this.constructor.name\n\n // Ensure proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype)\n\n // Capture stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n\n // copies status, code, etc.\n Object.assign(this, options)\n }\n\n /**\n * Returns a JSON-serializable representation of the error\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n code: this.errorCode,\n statusCode: this.statusCode,\n context: this.context,\n stack: this.stack,\n }\n }\n}\n\n/* 4xx client errors */\nexport class BadRequestError extends AmigoError {}\nexport class AuthenticationError extends AmigoError {}\nexport class PermissionError extends AmigoError {}\nexport class NotFoundError extends AmigoError {}\nexport class ConflictError extends AmigoError {}\nexport class RateLimitError extends AmigoError {}\n\n/* 5xx server errors */\nexport class ServerError extends AmigoError {}\nexport class ServiceUnavailableError extends ServerError {}\n\n/* Internal SDK errors */\nexport class ConfigurationError extends AmigoError {\n constructor(\n message: string,\n public field?: string\n ) {\n super(message)\n this.context = { field }\n }\n}\n\n/* Validation errors */\nexport class ValidationError extends BadRequestError {\n constructor(\n msg: string,\n public fieldErrors?: Record<string, string>\n ) {\n super(msg)\n }\n}\n\n/* Network-related errors */\nexport class NetworkError extends AmigoError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n public readonly request?: {\n url?: string\n method?: string\n }\n ) {\n super(message, { cause: originalError })\n this.context = { request }\n }\n}\n\n/* Parsing errors */\nexport class ParseError extends AmigoError {\n constructor(\n message: string,\n public readonly parseType: 'json' | 'response' | 'other',\n public readonly originalError?: Error\n ) {\n super(message, { cause: originalError })\n this.context = { parseType }\n }\n}\n\n/* Type guard functions */\nexport function isAmigoError(error: unknown): error is AmigoError {\n return error instanceof AmigoError\n}\n\n/* Error factory to create appropriate error instances from API responses */\nexport function createApiError(response: Response, body?: unknown): AmigoError {\n const map: Record<number, typeof AmigoError> = {\n 400: BadRequestError,\n 401: AuthenticationError,\n 403: PermissionError,\n 404: NotFoundError,\n 409: ConflictError,\n 422: ValidationError,\n 429: RateLimitError,\n 500: ServerError,\n 503: ServiceUnavailableError,\n }\n\n const errorMessageKeys = ['message', 'error', 'detail']\n\n const ErrorClass = map[response.status] ?? AmigoError\n let message = `HTTP ${response.status} ${response.statusText}`\n\n if (body && typeof body === 'object') {\n for (const key of errorMessageKeys) {\n if (key in body) {\n message = String((body as Record<string, unknown>)[key])\n break\n }\n }\n }\n\n const options = {\n status: response.status,\n code:\n body && typeof body === 'object' && 'code' in body\n ? (body as Record<string, unknown>).code\n : undefined,\n response: body,\n }\n\n const error = new ErrorClass(message, options)\n\n return error\n}\n\nexport function createErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const body = await parseResponseBody(response)\n throw createApiError(response, body)\n }\n },\n onError: async ({ error, request }) => {\n // Handle network-related errors consistently\n if (isNetworkError(error)) {\n throw new NetworkError(\n `Network error: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : new Error(String(error)),\n {\n url: request?.url,\n method: request?.method,\n }\n )\n }\n throw error\n },\n }\n}\n", "import { ParseError } from './errors'\n\n// Type helper to extract the data type from openapi-fetch responses\nexport type ExtractDataType<T> = T extends { data?: infer D } ? NonNullable<D> : never\n\n// Helper function to extract data from openapi-fetch responses\n// Since our middleware throws on errors, successful responses will have data\nexport async function extractData<T extends { data?: unknown }>(\n responsePromise: Promise<T>\n): Promise<ExtractDataType<T>> {\n const result = await responsePromise\n const data = (result as { data?: ExtractDataType<T> }).data\n\n if (data === undefined || data === null) {\n // Invariant: our error middleware throws for non-2xx responses.\n // If we reach here without data, treat as a parse/protocol error.\n throw new ParseError('Expected response data to be present for successful request', 'response')\n }\n\n return data\n}\n\n/**\n * Parse an NDJSON HTTP response body into an async generator of parsed JSON objects.\n * The generator yields one parsed object per line. Empty lines are skipped.\n */\nexport async function* parseNdjsonStream<T = unknown>(response: Response): AsyncGenerator<T> {\n const body = response.body\n if (!body) return\n\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let bufferedText = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n bufferedText += decoder.decode(value, { stream: true })\n\n let newlineIndex: number\n // Process all complete lines in the buffer\n while ((newlineIndex = bufferedText.indexOf('\\n')) !== -1) {\n const line = bufferedText.slice(0, newlineIndex).trim()\n bufferedText = bufferedText.slice(newlineIndex + 1)\n if (!line) continue\n try {\n yield JSON.parse(line) as T\n } catch (err) {\n throw new ParseError('Failed to parse NDJSON line', 'json', err as Error)\n }\n }\n }\n\n // Flush any trailing line without a newline\n const trailing = bufferedText.trim()\n if (trailing) {\n try {\n yield JSON.parse(trailing) as T\n } catch (err) {\n throw new ParseError('Failed to parse trailing NDJSON line', 'json', err as Error)\n }\n }\n } finally {\n reader.releaseLock()\n }\n}\n\n// Utility function to safely parse response bodies without throwing errors\nexport async function parseResponseBody(response: Response): Promise<unknown> {\n try {\n const text = await response.text()\n if (!text) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text // Return as string if not valid JSON\n }\n } catch {\n return undefined // Return undefined if any error occurs\n }\n}\n\n// Helper to detect network-related errors\nexport function isNetworkError(error: unknown): boolean {\n if (!(error instanceof Error)) return false\n\n return (\n error instanceof TypeError ||\n error.message.includes('fetch') ||\n error.message.includes('Failed to fetch') ||\n error.message.includes('Network request failed') ||\n error.message.includes('ECONNREFUSED') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('ENOTFOUND') ||\n error.message.includes('network')\n )\n}\n", "import createClient, { type Client } from 'openapi-fetch'\nimport { createErrorMiddleware } from './errors'\nimport { createAuthMiddleware } from './auth'\nimport type { paths } from '../generated/api-types'\nimport type { AmigoSdkConfig } from '..'\nimport { createRetryingFetch } from './retry'\n\nexport type AmigoFetch = Client<paths>\n\nexport function createAmigoFetch(config: AmigoSdkConfig, mockFetch?: typeof fetch): AmigoFetch {\n const wrappedFetch = createRetryingFetch(\n config.retry,\n mockFetch ?? (globalThis.fetch as typeof fetch)\n )\n\n const client = createClient<paths>({\n baseUrl: config.baseUrl,\n fetch: wrappedFetch,\n })\n\n // Apply error handling middleware first (to catch all errors)\n client.use(createErrorMiddleware())\n\n // Apply auth middleware after error handling (so auth errors are properly handled)\n client.use(createAuthMiddleware(config))\n\n return client\n}\n", "import type { Middleware } from 'openapi-fetch'\nimport type { components } from '../generated/api-types'\nimport type { AmigoSdkConfig } from '..'\nimport { AmigoError, AuthenticationError, NetworkError, ParseError, createApiError } from './errors'\nimport { isNetworkError, parseResponseBody } from './utils'\n\ntype SignInWithApiKeyResponse = components['schemas']['user__sign_in_with_api_key__Response']\n\n/** Helper function to trade API key for a bearer token */\nexport async function getBearerToken(config: AmigoSdkConfig): Promise<SignInWithApiKeyResponse> {\n const url = `${config.baseUrl}/v1/${config.orgId}/user/signin_with_api_key`\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'x-api-key': config.apiKey,\n 'x-api-key-id': config.apiKeyId,\n 'x-user-id': config.userId,\n },\n })\n\n if (!response.ok) {\n const body = await parseResponseBody(response)\n const apiError = createApiError(response, body)\n\n // Enhance authentication errors with additional context\n if (response.status === 401) {\n throw new AuthenticationError(`Authentication failed: ${apiError.message}`, {\n ...apiError,\n context: { ...apiError.context, endpoint: 'signin_with_api_key' },\n })\n }\n throw apiError\n }\n\n return (await response.json()) as SignInWithApiKeyResponse\n } catch (err) {\n // Re-throw our custom errors as-is\n if (err instanceof AmigoError) {\n throw err\n }\n\n // Handle network errors\n if (isNetworkError(err)) {\n throw new NetworkError('Failed to connect to authentication endpoint', err as Error, {\n url,\n method: 'POST',\n })\n }\n\n // Handle JSON parsing errors\n throw new ParseError(\n 'Failed to parse authentication response',\n 'json',\n err instanceof Error ? err : new Error(String(err))\n )\n }\n}\n\nexport function createAuthMiddleware(config: AmigoSdkConfig): Middleware {\n let token: SignInWithApiKeyResponse | null = null\n let refreshPromise: Promise<SignInWithApiKeyResponse> | null = null\n\n const shouldRefreshToken = (tokenData: SignInWithApiKeyResponse): boolean => {\n if (!tokenData.expires_at) return false\n\n const expiryTime = new Date(tokenData.expires_at).getTime()\n const currentTime = Date.now()\n const timeUntilExpiry = expiryTime - currentTime\n const refreshThreshold = 5 * 60 * 1000 // 5 minutes in milliseconds\n\n return timeUntilExpiry <= refreshThreshold\n }\n\n const ensureValidToken = async (): Promise<SignInWithApiKeyResponse> => {\n if (!token || shouldRefreshToken(token)) {\n if (!refreshPromise) {\n refreshPromise = getBearerToken(config)\n try {\n token = await refreshPromise\n } finally {\n refreshPromise = null\n }\n } else {\n token = await refreshPromise\n }\n }\n return token\n }\n\n return {\n onRequest: async ({ request }) => {\n try {\n const validToken = await ensureValidToken()\n if (validToken?.id_token) {\n request.headers.set('Authorization', `Bearer ${validToken.id_token}`)\n }\n } catch (error) {\n // Clear token and re-throw - getBearerToken already provides proper error types\n token = null\n throw error\n }\n return request\n },\n\n onResponse: async ({ response }) => {\n // Handle 401 responses by clearing token to force refresh on next request\n if (response.status === 401) {\n token = null\n }\n },\n\n onError: async ({ error }) => {\n // Clear token on any error to force refresh\n token = null\n throw error\n },\n }\n}\n", "export type RetryOptions = {\n /** Maximum number of attempts to make (default: 3) */\n maxAttempts?: number\n /** Base delay between attempts (default: 250ms) */\n backoffBaseMs?: number\n /** Maximum delay between attempts (default: 30s) */\n maxDelayMs?: number\n /** Status codes to retry on (default: 408, 429, 500, 502, 503, 504) */\n retryOnStatus?: Set<number>\n /** Methods to retry on (default: GET) */\n retryOnMethods?: Set<string>\n}\n\nconst DEFAULT_RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504])\nconst DEFAULT_RETRYABLE_METHODS = new Set(['GET']) as Set<string>\n\nexport function resolveRetryOptions(options?: RetryOptions): Required<RetryOptions> {\n return {\n maxAttempts: options?.maxAttempts ?? 3,\n backoffBaseMs: options?.backoffBaseMs ?? 250,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n retryOnStatus: new Set(options?.retryOnStatus ?? DEFAULT_RETRYABLE_STATUS),\n retryOnMethods: new Set(options?.retryOnMethods ?? DEFAULT_RETRYABLE_METHODS),\n }\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value))\n}\n\nfunction parseRetryAfterMs(headerValue: string | null, maxDelayMs: number): number | null {\n if (!headerValue) return null\n const seconds = Number(headerValue)\n if (Number.isFinite(seconds)) {\n return clamp(seconds * 1000, 0, maxDelayMs)\n }\n const date = new Date(headerValue)\n const ms = date.getTime() - Date.now()\n if (Number.isFinite(ms)) {\n return clamp(ms, 0, maxDelayMs)\n }\n return null\n}\n\nfunction computeBackoffWithJitterMs(\n attemptIndexZeroBased: number,\n baseMs: number,\n capMs: number\n): number {\n const windowMs = Math.min(capMs, baseMs * Math.pow(2, attemptIndexZeroBased))\n return Math.random() * windowMs\n}\n\nfunction isAbortError(err: unknown): boolean {\n return typeof err === 'object' && err !== null && 'name' in err && err['name'] === 'AbortError'\n}\n\nfunction isNetworkError(err: unknown): boolean {\n // Undici & browsers use TypeError for network failures\n return err instanceof TypeError && !isAbortError(err)\n}\n\nasync function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) {\n signal?.throwIfAborted?.()\n return\n }\n await new Promise<void>((resolve, reject) => {\n const rejectWith =\n signal?.reason instanceof Error ? signal.reason : (signal?.reason ?? new Error('AbortError'))\n\n if (signal?.aborted) {\n reject(rejectWith)\n return\n }\n const t = setTimeout(() => {\n off()\n resolve()\n }, ms)\n const onAbort = () => {\n off()\n clearTimeout(t)\n reject(rejectWith)\n }\n const off = () => signal?.removeEventListener('abort', onAbort)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\nexport function createRetryingFetch(\n retryOptions?: RetryOptions,\n baseFetch?: typeof fetch\n): typeof fetch {\n const resolved = resolveRetryOptions(retryOptions)\n const underlying: typeof fetch = baseFetch ?? (globalThis.fetch as typeof fetch)\n\n const retryingFetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> => {\n const inputMethod =\n typeof Request !== 'undefined' && input instanceof Request ? input.method : undefined\n const method = ((init?.method ?? inputMethod ?? 'GET') as string).toUpperCase()\n const signal = init?.signal\n\n const isMethodRetryableByDefault = resolved.retryOnMethods.has(method)\n const maxAttempts = Math.max(1, resolved.maxAttempts)\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n let response: Response | null = null\n let error: unknown = null\n\n try {\n response = await underlying(input, init)\n } catch (err) {\n error = err\n }\n\n if (!error && response && response.ok) {\n return response\n }\n\n let shouldRetry = false\n let delayMs: number | null = null\n\n if (isNetworkError(error)) {\n shouldRetry = isMethodRetryableByDefault\n if (shouldRetry) {\n delayMs = computeBackoffWithJitterMs(\n attempt - 1,\n resolved.backoffBaseMs,\n resolved.maxDelayMs\n )\n }\n } else if (response) {\n const status = response.status\n if (method === 'POST') {\n if (status === 429) {\n const ra = response.headers.get('Retry-After')\n const parsed = parseRetryAfterMs(ra, resolved.maxDelayMs)\n if (parsed !== null) {\n shouldRetry = true\n delayMs = parsed\n }\n }\n } else if (isMethodRetryableByDefault && resolved.retryOnStatus.has(status)) {\n const ra = response.headers.get('Retry-After')\n delayMs =\n parseRetryAfterMs(ra, resolved.maxDelayMs) ??\n computeBackoffWithJitterMs(attempt - 1, resolved.backoffBaseMs, resolved.maxDelayMs)\n shouldRetry = true\n }\n }\n\n const attemptsRemain = attempt < maxAttempts\n if (!shouldRetry || !attemptsRemain) {\n if (error) throw error\n return response as Response\n }\n\n if (signal?.aborted) {\n if (error) throw error\n return response as Response\n }\n\n await abortableSleep(delayMs ?? 0, signal ?? undefined)\n }\n\n throw new Error('Retry loop exited unexpectedly')\n }\n\n return retryingFetch\n}\n\nexport type { RetryOptions as AmigoRetryOptions }\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { operations } from '../generated/api-types'\n\nexport class OrganizationResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n /**\n * Get organization details\n * @param headers - The headers\n * @returns The organization details\n */\n async getOrganization(headers?: operations['get-organization']['parameters']['header']) {\n return extractData(\n this.c.GET('/v1/{organization}/organization/', {\n params: { path: { organization: this.orgId } },\n headers,\n })\n )\n }\n}\n", "import { BadRequestError } from '../core/errors'\nimport type { AmigoFetch } from '../core/openapi-client'\nimport { extractData, parseNdjsonStream } from '../core/utils'\nimport type { components, operations } from '../generated/api-types'\n\ntype VoiceData = Blob | Uint8Array | ReadableStream<Uint8Array>\nexport type InteractionInput = string | VoiceData\n\ntype InteractQuery = operations['interact-with-conversation']['parameters']['query']\ntype InteractQuerySerialized = Omit<InteractQuery, 'request_audio_config'> & {\n request_audio_config?: string | null\n}\n\nexport class ConversationResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n async createConversation(\n body: components['schemas']['conversation__create_conversation__Request'],\n queryParams: operations['create-conversation']['parameters']['query'],\n headers?: operations['create-conversation']['parameters']['header'],\n options?: { signal?: AbortSignal }\n ) {\n const resp = await this.c.POST('/v1/{organization}/conversation/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n body,\n headers: {\n Accept: 'application/x-ndjson',\n ...(headers ?? {}),\n } as operations['create-conversation']['parameters']['header'],\n // Ensure we receive a stream for NDJSON\n parseAs: 'stream',\n ...(options?.signal && { signal: options.signal }),\n })\n\n // onResponse middleware throws for non-2xx; if we reach here, it's OK.\n return parseNdjsonStream<components['schemas']['conversation__create_conversation__Response']>(\n resp.response\n )\n }\n\n async interactWithConversation(\n conversationId: string,\n input: InteractionInput,\n queryParams: operations['interact-with-conversation']['parameters']['query'],\n headers?: operations['interact-with-conversation']['parameters']['header'],\n options?: { signal?: AbortSignal }\n ) {\n // Build body based on requested format, then perform a single POST\n let bodyToSend: FormData | VoiceData\n\n // Prepare headers; we'll merge user-supplied headers and adjust per format\n const mergedHeaders: Record<string, unknown> = {\n Accept: 'application/x-ndjson',\n ...(headers ?? {}),\n }\n\n if (queryParams.request_format === 'text') {\n if (typeof input !== 'string') {\n throw new BadRequestError(\"textMessage is required when request_format is 'text'\")\n }\n const form = new FormData()\n const blob = new Blob([input], { type: 'text/plain; charset=utf-8' })\n form.append('recorded_message', blob, 'message.txt')\n bodyToSend = form\n } else if (queryParams.request_format === 'voice') {\n if (typeof input === 'string') {\n throw new BadRequestError(\n \"voice input must be a byte source when request_format is 'voice'\"\n )\n }\n bodyToSend = input\n } else {\n throw new BadRequestError('Unsupported or missing request_format in params')\n }\n\n // For text/FormData, do NOT set Content-Type; fetch will set multipart boundary\n if (queryParams.request_format === 'text') {\n delete mergedHeaders['content-type']\n delete mergedHeaders['Content-Type']\n }\n\n // For voice bytes, allow caller to specify Content-Type; if absent and input is a Blob with a type, use it\n if (queryParams.request_format === 'voice') {\n const hasContentType =\n mergedHeaders['content-type'] !== undefined || mergedHeaders['Content-Type'] !== undefined\n if (!hasContentType && typeof Blob !== 'undefined' && input instanceof Blob && input.type) {\n mergedHeaders['content-type'] = input.type\n }\n }\n\n const headersToSend =\n mergedHeaders as unknown as operations['interact-with-conversation']['parameters']['header']\n\n // Normalize nested object params that must be sent as JSON strings\n const normalizedQuery: InteractQuerySerialized = {\n ...queryParams,\n request_audio_config:\n typeof queryParams.request_audio_config === 'object' &&\n queryParams.request_audio_config !== null\n ? JSON.stringify(queryParams.request_audio_config)\n : (queryParams.request_audio_config ?? undefined),\n }\n\n const resp = await this.c.POST('/v1/{organization}/conversation/{conversation_id}/interact', {\n params: {\n path: { organization: this.orgId, conversation_id: conversationId },\n query: normalizedQuery as unknown as InteractQuery,\n header: headersToSend,\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body: bodyToSend as any, // FormData/Blob not represented in generated OpenAPI types\n parseAs: 'stream',\n ...(options?.signal && { signal: options.signal }),\n })\n\n return parseNdjsonStream<\n components['schemas']['conversation__interact_with_conversation__Response']\n >(resp.response)\n }\n\n async getConversations(\n queryParams?: operations['get-conversations']['parameters']['query'],\n headers?: operations['get-conversations']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n\n async getConversationMessages(\n conversationId: string,\n queryParams?: operations['get-conversation-messages']['parameters']['query'],\n headers?: operations['get-conversation-messages']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/{conversation_id}/messages/', {\n params: {\n path: { organization: this.orgId, conversation_id: conversationId },\n query: queryParams,\n },\n headers,\n })\n )\n }\n\n async finishConversation(\n conversationId: string,\n headers?: operations['finish-conversation']['parameters']['header']\n ) {\n await this.c.POST('/v1/{organization}/conversation/{conversation_id}/finish/', {\n params: { path: { organization: this.orgId, conversation_id: conversationId } },\n headers,\n // No content is expected; parse as text to access raw Response\n parseAs: 'text',\n })\n return\n }\n\n async recommendResponsesForInteraction(\n conversationId: string,\n interactionId: string,\n body?: { context?: string },\n headers?: operations['recommend-responses-for-interaction']['parameters']['header']\n ) {\n return extractData(\n this.c.POST(\n '/v1/{organization}/conversation/{conversation_id}/interaction/{interaction_id}/recommend_responses',\n {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n interaction_id: interactionId,\n },\n },\n body,\n headers,\n }\n )\n )\n }\n\n async getInteractionInsights(\n conversationId: string,\n interactionId: string,\n headers?: operations['get-interaction-insights']['parameters']['header']\n ) {\n return extractData(\n this.c.GET(\n '/v1/{organization}/conversation/{conversation_id}/interaction/{interaction_id}/insights',\n {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n interaction_id: interactionId,\n },\n },\n headers,\n }\n )\n )\n }\n\n // Note: the OpenAPI response schema isn't correct for this endpoint.\n // TODO -- fix response typing.\n async getMessageSource(\n conversationId: string,\n messageId: string,\n headers?: operations['retrieve-message-source']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/{conversation_id}/messages/{message_id}/source', {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n message_id: messageId,\n },\n },\n headers,\n })\n )\n }\n\n async generateConversationStarters(\n body: components['schemas']['conversation__generate_conversation_starter__Request'],\n headers?: operations['generate-conversation-starter']['parameters']['header']\n ) {\n return extractData(\n this.c.POST('/v1/{organization}/conversation/conversation_starter', {\n params: { path: { organization: this.orgId } },\n body,\n headers,\n })\n )\n }\n}\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { operations } from '../generated/api-types'\n\nexport class ServiceResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n /**\n * Get services\n * @param headers - The headers\n * @returns The services\n */\n async getServices(\n queryParams?: operations['get-services']['parameters']['query'],\n headers?: operations['get-services']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/service/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n}\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { components, operations } from '../generated/api-types'\n\nexport class UserResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n async getUsers(\n queryParams?: operations['get-users']['parameters']['query'],\n headers?: operations['get-users']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/user/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n\n async createUser(\n body: components['schemas']['user__create_invited_user__Request'],\n headers?: operations['create-invited-user']['parameters']['header']\n ) {\n return extractData(\n this.c.POST('/v1/{organization}/user/', {\n params: { path: { organization: this.orgId } },\n body,\n headers,\n })\n )\n }\n\n async deleteUser(userId: string, headers?: operations['delete-user']['parameters']['header']) {\n // DELETE endpoints returns no content (e.g., 204 No Content).\n // Our middleware already throws on non-2xx responses, so simply await the call.\n await this.c.DELETE('/v1/{organization}/user/{requested_user_id}', {\n params: { path: { organization: this.orgId, requested_user_id: userId } },\n headers,\n })\n return\n }\n\n async updateUser(\n userId: string,\n body: components['schemas']['user__update_user_info__Request'],\n headers?: operations['update-user-info']['parameters']['header']\n ) {\n // UPDATE endpoint returns no content (e.g., 204 No Content).\n // Our middleware already throws on non-2xx responses, so simply await the call.\n await this.c.POST('/v1/{organization}/user/{requested_user_id}', {\n params: { path: { organization: this.orgId, requested_user_id: userId } },\n body,\n headers,\n })\n return\n }\n\n async getUserModel(\n userId: string,\n headers?: operations['get-user-model']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/user/{user_id}/user_model', {\n params: { path: { organization: this.orgId, user_id: userId } },\n headers,\n })\n )\n }\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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C,OAAO,QAAQ;AAClB,UAAM,IAAI,mBAAmB,uBAAuB,QAAQ;AAAA,EAC9D;AACA,MAAI,CAAC,OAAO,UAAU;AACpB,UAAM,IAAI,mBAAmB,0BAA0B,UAAU;AAAA,EACnE;AACA,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,mBAAmB,uBAAuB,QAAQ;AAAA,EAC9D;AACA,MAAI,CAAC,OAAO,OAAO;AACjB,UAAM,IAAI,mBAAmB,+BAA+B,OAAO;AAAA,EACrE;AACA,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,UAAU;AAAA,EACnB;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import { ConfigurationError } from './core/errors'\nimport { createAmigoFetch } from './core/openapi-client'\nimport { OrganizationResource } from './resources/organization'\nimport { ConversationResource } from './resources/conversation'\nimport { ServiceResource } from './resources/services'\nimport { UserResource } from './resources/user'\nimport type { RetryOptions } from './core/retry'\n\nexport interface AmigoSdkConfig {\n /** API key from Amigo dashboard */\n apiKey: string\n /** API-key ID from Amigo dashboard */\n apiKeyId: string\n /** User ID on whose behalf the request is made */\n userId: string\n /** The Organization ID */\n orgId: string\n /** Base URL of the Amigo API */\n baseUrl?: string\n /** Retry configuration for HTTP requests */\n retry?: RetryOptions\n}\n\nconst defaultBaseUrl = 'https://api.amigo.ai'\n\nexport class AmigoClient {\n readonly organizations: OrganizationResource\n readonly conversations: ConversationResource\n readonly services: ServiceResource\n readonly users: UserResource\n readonly config: AmigoSdkConfig\n\n constructor(config: AmigoSdkConfig) {\n this.config = validateConfig(config)\n\n const api = createAmigoFetch(this.config)\n this.organizations = new OrganizationResource(api, this.config.orgId)\n this.conversations = new ConversationResource(api, this.config.orgId)\n this.services = new ServiceResource(api, this.config.orgId)\n this.users = new UserResource(api, this.config.orgId)\n }\n}\n\nfunction validateConfig(config: AmigoSdkConfig) {\n if (!config.apiKey) {\n throw new ConfigurationError('API key is required', 'apiKey')\n }\n if (!config.apiKeyId) {\n throw new ConfigurationError('API key ID is required', 'apiKeyId')\n }\n if (!config.userId) {\n throw new ConfigurationError('User ID is required', 'userId')\n }\n if (!config.orgId) {\n throw new ConfigurationError('Organization ID is required', 'orgId')\n }\n if (!config.baseUrl) {\n config.baseUrl = defaultBaseUrl\n }\n return config\n}\n\n// Export all errors as a namespace to avoid polluting the main import space\nexport * as errors from './core/errors'\n\n// Re-export useful types for consumers\nexport type { components, operations, paths } from './generated/api-types'\n", "import type { Middleware } from 'openapi-fetch'\nimport { isNetworkError, parseResponseBody } from './utils'\n\n/**\n * Base error class for all Amigo SDK errors.\n * Provides common functionality and error identification.\n */\nexport class AmigoError extends Error {\n /**\n * Unique error code for programmatic error handling\n */\n readonly errorCode?: string\n\n /**\n * HTTP status code if applicable\n */\n readonly statusCode?: number\n\n /**\n * Additional context data\n */\n context?: Record<string, unknown>\n\n constructor(message: string, options?: Record<string, unknown>) {\n super(message)\n this.name = this.constructor.name\n\n // Ensure proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype)\n\n // Capture stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n\n // copies status, code, etc.\n Object.assign(this, options)\n }\n\n /**\n * Returns a JSON-serializable representation of the error\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n code: this.errorCode,\n statusCode: this.statusCode,\n context: this.context,\n stack: this.stack,\n }\n }\n}\n\n/* 4xx client errors */\nexport class BadRequestError extends AmigoError {}\nexport class AuthenticationError extends AmigoError {}\nexport class PermissionError extends AmigoError {}\nexport class NotFoundError extends AmigoError {}\nexport class ConflictError extends AmigoError {}\nexport class RateLimitError extends AmigoError {}\n\n/* 5xx server errors */\nexport class ServerError extends AmigoError {}\nexport class ServiceUnavailableError extends ServerError {}\n\n/* Internal SDK errors */\nexport class ConfigurationError extends AmigoError {\n constructor(\n message: string,\n public field?: string\n ) {\n super(message)\n this.context = { field }\n }\n}\n\n/* Validation errors */\nexport class ValidationError extends BadRequestError {\n constructor(\n msg: string,\n public fieldErrors?: Record<string, string>\n ) {\n super(msg)\n }\n}\n\n/* Network-related errors */\nexport class NetworkError extends AmigoError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n public readonly request?: {\n url?: string\n method?: string\n }\n ) {\n super(message, { cause: originalError })\n this.context = { request }\n }\n}\n\n/* Parsing errors */\nexport class ParseError extends AmigoError {\n constructor(\n message: string,\n public readonly parseType: 'json' | 'response' | 'other',\n public readonly originalError?: Error\n ) {\n super(message, { cause: originalError })\n this.context = { parseType }\n }\n}\n\n/* Type guard functions */\nexport function isAmigoError(error: unknown): error is AmigoError {\n return error instanceof AmigoError\n}\n\n/* Error factory to create appropriate error instances from API responses */\nexport function createApiError(response: Response, body?: unknown): AmigoError {\n const map: Record<number, typeof AmigoError> = {\n 400: BadRequestError,\n 401: AuthenticationError,\n 403: PermissionError,\n 404: NotFoundError,\n 409: ConflictError,\n 422: ValidationError,\n 429: RateLimitError,\n 500: ServerError,\n 503: ServiceUnavailableError,\n }\n\n const errorMessageKeys = ['message', 'error', 'detail']\n\n const ErrorClass = map[response.status] ?? AmigoError\n let message = `HTTP ${response.status} ${response.statusText}`\n\n if (body && typeof body === 'object') {\n for (const key of errorMessageKeys) {\n if (key in body) {\n message = String((body as Record<string, unknown>)[key])\n break\n }\n }\n }\n\n const options = {\n status: response.status,\n code:\n body && typeof body === 'object' && 'code' in body\n ? (body as Record<string, unknown>).code\n : undefined,\n response: body,\n }\n\n const error = new ErrorClass(message, options)\n\n return error\n}\n\nexport function createErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const body = await parseResponseBody(response)\n throw createApiError(response, body)\n }\n },\n onError: async ({ error, request }) => {\n // Handle network-related errors consistently\n if (isNetworkError(error)) {\n throw new NetworkError(\n `Network error: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : new Error(String(error)),\n {\n url: request?.url,\n method: request?.method,\n }\n )\n }\n throw error\n },\n }\n}\n", "import { ParseError } from './errors'\n\n// Type helper to extract the data type from openapi-fetch responses\nexport type ExtractDataType<T> = T extends { data?: infer D } ? NonNullable<D> : never\n\n// Helper function to extract data from openapi-fetch responses\n// Since our middleware throws on errors, successful responses will have data\nexport async function extractData<T extends { data?: unknown }>(\n responsePromise: Promise<T>\n): Promise<ExtractDataType<T>> {\n const result = await responsePromise\n const data = (result as { data?: ExtractDataType<T> }).data\n\n if (data === undefined || data === null) {\n // Invariant: our error middleware throws for non-2xx responses.\n // If we reach here without data, treat as a parse/protocol error.\n throw new ParseError('Expected response data to be present for successful request', 'response')\n }\n\n return data\n}\n\n/**\n * Parse an NDJSON HTTP response body into an async generator of parsed JSON objects.\n * The generator yields one parsed object per line. Empty lines are skipped.\n */\nexport async function* parseNdjsonStream<T = unknown>(response: Response): AsyncGenerator<T> {\n const body = response.body\n if (!body) return\n\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let bufferedText = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n bufferedText += decoder.decode(value, { stream: true })\n\n let newlineIndex: number\n // Process all complete lines in the buffer\n while ((newlineIndex = bufferedText.indexOf('\\n')) !== -1) {\n const line = bufferedText.slice(0, newlineIndex).trim()\n bufferedText = bufferedText.slice(newlineIndex + 1)\n if (!line) continue\n try {\n yield JSON.parse(line) as T\n } catch (err) {\n throw new ParseError('Failed to parse NDJSON line', 'json', err as Error)\n }\n }\n }\n\n // Flush any trailing line without a newline\n const trailing = bufferedText.trim()\n if (trailing) {\n try {\n yield JSON.parse(trailing) as T\n } catch (err) {\n throw new ParseError('Failed to parse trailing NDJSON line', 'json', err as Error)\n }\n }\n } finally {\n reader.releaseLock()\n }\n}\n\n// Utility function to safely parse response bodies without throwing errors\nexport async function parseResponseBody(response: Response): Promise<unknown> {\n try {\n const text = await response.text()\n if (!text) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text // Return as string if not valid JSON\n }\n } catch {\n return undefined // Return undefined if any error occurs\n }\n}\n\n// Helper to detect network-related errors\nexport function isNetworkError(error: unknown): boolean {\n if (!(error instanceof Error)) return false\n\n return (\n error instanceof TypeError ||\n error.message.includes('fetch') ||\n error.message.includes('Failed to fetch') ||\n error.message.includes('Network request failed') ||\n error.message.includes('ECONNREFUSED') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('ENOTFOUND') ||\n error.message.includes('network')\n )\n}\n", "import createClient, { type Client } from 'openapi-fetch'\nimport { createErrorMiddleware } from './errors'\nimport { createAuthMiddleware } from './auth'\nimport type { paths } from '../generated/api-types'\nimport type { AmigoSdkConfig } from '..'\nimport { createRetryingFetch } from './retry'\n\nexport type AmigoFetch = Client<paths>\n\nexport function createAmigoFetch(config: AmigoSdkConfig, mockFetch?: typeof fetch): AmigoFetch {\n const wrappedFetch = createRetryingFetch(\n config.retry,\n mockFetch ?? (globalThis.fetch as typeof fetch)\n )\n\n const client = createClient<paths>({\n baseUrl: config.baseUrl,\n fetch: wrappedFetch,\n })\n\n // Apply error handling middleware first (to catch all errors)\n client.use(createErrorMiddleware())\n\n // Apply auth middleware after error handling (so auth errors are properly handled)\n client.use(createAuthMiddleware(config))\n\n return client\n}\n", "import type { Middleware } from 'openapi-fetch'\nimport type { components } from '../generated/api-types'\nimport type { AmigoSdkConfig } from '..'\nimport { AmigoError, AuthenticationError, NetworkError, ParseError, createApiError } from './errors'\nimport { isNetworkError, parseResponseBody } from './utils'\n\ntype SignInWithApiKeyResponse = components['schemas']['user__sign_in_with_api_key__Response']\n\n/** Helper function to trade API key for a bearer token */\nexport async function getBearerToken(config: AmigoSdkConfig): Promise<SignInWithApiKeyResponse> {\n const url = `${config.baseUrl}/v1/${config.orgId}/user/signin_with_api_key`\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'x-api-key': config.apiKey,\n 'x-api-key-id': config.apiKeyId,\n 'x-user-id': config.userId,\n },\n })\n\n if (!response.ok) {\n const body = await parseResponseBody(response)\n const apiError = createApiError(response, body)\n\n // Enhance authentication errors with additional context\n if (response.status === 401) {\n throw new AuthenticationError(`Authentication failed: ${apiError.message}`, {\n ...apiError,\n context: { ...apiError.context, endpoint: 'signin_with_api_key' },\n })\n }\n throw apiError\n }\n\n return (await response.json()) as SignInWithApiKeyResponse\n } catch (err) {\n // Re-throw our custom errors as-is\n if (err instanceof AmigoError) {\n throw err\n }\n\n // Handle network errors\n if (isNetworkError(err)) {\n throw new NetworkError('Failed to connect to authentication endpoint', err as Error, {\n url,\n method: 'POST',\n })\n }\n\n // Handle JSON parsing errors\n throw new ParseError(\n 'Failed to parse authentication response',\n 'json',\n err instanceof Error ? err : new Error(String(err))\n )\n }\n}\n\nexport function createAuthMiddleware(config: AmigoSdkConfig): Middleware {\n let token: SignInWithApiKeyResponse | null = null\n let refreshPromise: Promise<SignInWithApiKeyResponse> | null = null\n\n const shouldRefreshToken = (tokenData: SignInWithApiKeyResponse): boolean => {\n if (!tokenData.expires_at) return false\n\n const expiryTime = new Date(tokenData.expires_at).getTime()\n const currentTime = Date.now()\n const timeUntilExpiry = expiryTime - currentTime\n const refreshThreshold = 5 * 60 * 1000 // 5 minutes in milliseconds\n\n return timeUntilExpiry <= refreshThreshold\n }\n\n const ensureValidToken = async (): Promise<SignInWithApiKeyResponse> => {\n if (!token || shouldRefreshToken(token)) {\n if (!refreshPromise) {\n refreshPromise = getBearerToken(config)\n try {\n token = await refreshPromise\n } finally {\n refreshPromise = null\n }\n } else {\n token = await refreshPromise\n }\n }\n return token\n }\n\n return {\n onRequest: async ({ request }) => {\n try {\n const validToken = await ensureValidToken()\n if (validToken?.id_token) {\n request.headers.set('Authorization', `Bearer ${validToken.id_token}`)\n }\n } catch (error) {\n // Clear token and re-throw - getBearerToken already provides proper error types\n token = null\n throw error\n }\n return request\n },\n\n onResponse: async ({ response }) => {\n // Handle 401 responses by clearing token to force refresh on next request\n if (response.status === 401) {\n token = null\n }\n },\n\n onError: async ({ error }) => {\n // Clear token on any error to force refresh\n token = null\n throw error\n },\n }\n}\n", "export type RetryOptions = {\n /** Maximum number of attempts to make (default: 3) */\n maxAttempts?: number\n /** Base delay between attempts (default: 250ms) */\n backoffBaseMs?: number\n /** Maximum delay between attempts (default: 30s) */\n maxDelayMs?: number\n /** Status codes to retry on (default: 408, 429, 500, 502, 503, 504) */\n retryOnStatus?: Set<number>\n /** Methods to retry on (default: GET) */\n retryOnMethods?: Set<string>\n}\n\nconst DEFAULT_RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504])\nconst DEFAULT_RETRYABLE_METHODS = new Set(['GET']) as Set<string>\n\nexport function resolveRetryOptions(options?: RetryOptions): Required<RetryOptions> {\n return {\n maxAttempts: options?.maxAttempts ?? 3,\n backoffBaseMs: options?.backoffBaseMs ?? 250,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n retryOnStatus: new Set(options?.retryOnStatus ?? DEFAULT_RETRYABLE_STATUS),\n retryOnMethods: new Set(options?.retryOnMethods ?? DEFAULT_RETRYABLE_METHODS),\n }\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value))\n}\n\nfunction parseRetryAfterMs(headerValue: string | null, maxDelayMs: number): number | null {\n if (!headerValue) return null\n const seconds = Number(headerValue)\n if (Number.isFinite(seconds)) {\n return clamp(seconds * 1000, 0, maxDelayMs)\n }\n const date = new Date(headerValue)\n const ms = date.getTime() - Date.now()\n if (Number.isFinite(ms)) {\n return clamp(ms, 0, maxDelayMs)\n }\n return null\n}\n\nfunction computeBackoffWithJitterMs(\n attemptIndexZeroBased: number,\n baseMs: number,\n capMs: number\n): number {\n const windowMs = Math.min(capMs, baseMs * Math.pow(2, attemptIndexZeroBased))\n return Math.random() * windowMs\n}\n\nfunction isAbortError(err: unknown): boolean {\n return typeof err === 'object' && err !== null && 'name' in err && err['name'] === 'AbortError'\n}\n\nfunction isNetworkError(err: unknown): boolean {\n // Undici & browsers use TypeError for network failures\n return err instanceof TypeError && !isAbortError(err)\n}\n\nasync function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) {\n signal?.throwIfAborted?.()\n return\n }\n await new Promise<void>((resolve, reject) => {\n const rejectWith =\n signal?.reason instanceof Error ? signal.reason : (signal?.reason ?? new Error('AbortError'))\n\n if (signal?.aborted) {\n reject(rejectWith)\n return\n }\n const t = setTimeout(() => {\n off()\n resolve()\n }, ms)\n const onAbort = () => {\n off()\n clearTimeout(t)\n reject(rejectWith)\n }\n const off = () => signal?.removeEventListener('abort', onAbort)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\nexport function createRetryingFetch(\n retryOptions?: RetryOptions,\n baseFetch?: typeof fetch\n): typeof fetch {\n const resolved = resolveRetryOptions(retryOptions)\n const underlying: typeof fetch = baseFetch ?? (globalThis.fetch as typeof fetch)\n\n const retryingFetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> => {\n const inputMethod =\n typeof Request !== 'undefined' && input instanceof Request ? input.method : undefined\n const method = ((init?.method ?? inputMethod ?? 'GET') as string).toUpperCase()\n const signal = init?.signal\n\n const isMethodRetryableByDefault = resolved.retryOnMethods.has(method)\n const maxAttempts = Math.max(1, resolved.maxAttempts)\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n let response: Response | null = null\n let error: unknown = null\n\n try {\n response = await underlying(input, init)\n } catch (err) {\n error = err\n }\n\n if (!error && response && response.ok) {\n return response\n }\n\n let shouldRetry = false\n let delayMs: number | null = null\n\n if (isNetworkError(error)) {\n shouldRetry = isMethodRetryableByDefault\n if (shouldRetry) {\n delayMs = computeBackoffWithJitterMs(\n attempt - 1,\n resolved.backoffBaseMs,\n resolved.maxDelayMs\n )\n }\n } else if (response) {\n const status = response.status\n if (method === 'POST') {\n if (status === 429) {\n const ra = response.headers.get('Retry-After')\n const parsed = parseRetryAfterMs(ra, resolved.maxDelayMs)\n if (parsed !== null) {\n shouldRetry = true\n delayMs = parsed\n }\n }\n } else if (isMethodRetryableByDefault && resolved.retryOnStatus.has(status)) {\n const ra = response.headers.get('Retry-After')\n delayMs =\n parseRetryAfterMs(ra, resolved.maxDelayMs) ??\n computeBackoffWithJitterMs(attempt - 1, resolved.backoffBaseMs, resolved.maxDelayMs)\n shouldRetry = true\n }\n }\n\n const attemptsRemain = attempt < maxAttempts\n if (!shouldRetry || !attemptsRemain) {\n if (error) throw error\n return response as Response\n }\n\n if (signal?.aborted) {\n if (error) throw error\n return response as Response\n }\n\n await abortableSleep(delayMs ?? 0, signal ?? undefined)\n }\n\n throw new Error('Retry loop exited unexpectedly')\n }\n\n return retryingFetch\n}\n\nexport type { RetryOptions as AmigoRetryOptions }\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { operations } from '../generated/api-types'\n\nexport class OrganizationResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n /**\n * Get organization details\n * @param headers - The headers\n * @returns The organization details\n */\n async getOrganization(headers?: operations['get-organization']['parameters']['header']) {\n return extractData(\n this.c.GET('/v1/{organization}/organization/', {\n params: { path: { organization: this.orgId } },\n headers,\n })\n )\n }\n}\n", "import { BadRequestError } from '../core/errors'\nimport type { AmigoFetch } from '../core/openapi-client'\nimport { extractData, parseNdjsonStream } from '../core/utils'\nimport type { components, operations } from '../generated/api-types'\n\ntype VoiceData = Blob | Uint8Array | ReadableStream<Uint8Array>\nexport type InteractionInput = string | VoiceData\n\ntype InteractQuery = operations['interact-with-conversation']['parameters']['query']\ntype InteractQuerySerialized = Omit<InteractQuery, 'request_audio_config'> & {\n request_audio_config?: string | null\n}\n\nexport class ConversationResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n async createConversation(\n body: components['schemas']['conversation__create_conversation__Request'],\n queryParams: operations['create-conversation']['parameters']['query'],\n headers?: operations['create-conversation']['parameters']['header'],\n options?: { signal?: AbortSignal }\n ) {\n const resp = await this.c.POST('/v1/{organization}/conversation/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n body,\n headers: {\n Accept: 'application/x-ndjson',\n ...(headers ?? {}),\n } as operations['create-conversation']['parameters']['header'],\n // Ensure we receive a stream for NDJSON\n parseAs: 'stream',\n ...(options?.signal && { signal: options.signal }),\n })\n\n // onResponse middleware throws for non-2xx; if we reach here, it's OK.\n return parseNdjsonStream<components['schemas']['conversation__create_conversation__Response']>(\n resp.response\n )\n }\n\n async interactWithConversation(\n conversationId: string,\n input: InteractionInput,\n queryParams: operations['interact-with-conversation']['parameters']['query'],\n headers?: operations['interact-with-conversation']['parameters']['header'],\n options?: { signal?: AbortSignal }\n ) {\n // Build body based on requested format, then perform a single POST\n let bodyToSend: FormData | VoiceData\n\n // Prepare headers; we'll merge user-supplied headers and adjust per format\n const mergedHeaders: Record<string, unknown> = {\n Accept: 'application/x-ndjson',\n ...(headers ?? {}),\n }\n\n if (queryParams.request_format === 'text') {\n if (typeof input !== 'string') {\n throw new BadRequestError(\"textMessage is required when request_format is 'text'\")\n }\n const form = new FormData()\n form.append('initial_message_type', 'user-message')\n form.append('recorded_message', input)\n bodyToSend = form\n } else if (queryParams.request_format === 'voice') {\n if (typeof input === 'string') {\n throw new BadRequestError(\n \"voice input must be a byte source when request_format is 'voice'\"\n )\n }\n bodyToSend = input\n } else {\n throw new BadRequestError('Unsupported or missing request_format in params')\n }\n\n // For text/FormData, do NOT set Content-Type; fetch will set multipart boundary\n if (queryParams.request_format === 'text') {\n delete mergedHeaders['content-type']\n delete mergedHeaders['Content-Type']\n }\n\n // For voice bytes, allow caller to specify Content-Type; if absent and input is a Blob with a type, use it\n if (queryParams.request_format === 'voice') {\n const hasContentType =\n mergedHeaders['content-type'] !== undefined || mergedHeaders['Content-Type'] !== undefined\n if (!hasContentType && typeof Blob !== 'undefined' && input instanceof Blob && input.type) {\n mergedHeaders['content-type'] = input.type\n }\n }\n\n const headersToSend =\n mergedHeaders as unknown as operations['interact-with-conversation']['parameters']['header']\n\n // Normalize nested object params that must be sent as JSON strings\n const normalizedQuery: InteractQuerySerialized = {\n ...queryParams,\n request_audio_config:\n typeof queryParams.request_audio_config === 'object' &&\n queryParams.request_audio_config !== null\n ? JSON.stringify(queryParams.request_audio_config)\n : (queryParams.request_audio_config ?? undefined),\n }\n\n const resp = await this.c.POST('/v1/{organization}/conversation/{conversation_id}/interact', {\n params: {\n path: { organization: this.orgId, conversation_id: conversationId },\n query: normalizedQuery as unknown as InteractQuery,\n header: headersToSend,\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body: bodyToSend as any, // FormData/Blob not represented in generated OpenAPI types\n parseAs: 'stream',\n ...(options?.signal && { signal: options.signal }),\n })\n\n return parseNdjsonStream<\n components['schemas']['conversation__interact_with_conversation__Response']\n >(resp.response)\n }\n\n async getConversations(\n queryParams?: operations['get-conversations']['parameters']['query'],\n headers?: operations['get-conversations']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n\n async getConversationMessages(\n conversationId: string,\n queryParams?: operations['get-conversation-messages']['parameters']['query'],\n headers?: operations['get-conversation-messages']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/{conversation_id}/messages/', {\n params: {\n path: { organization: this.orgId, conversation_id: conversationId },\n query: queryParams,\n },\n headers,\n })\n )\n }\n\n async finishConversation(\n conversationId: string,\n headers?: operations['finish-conversation']['parameters']['header']\n ) {\n await this.c.POST('/v1/{organization}/conversation/{conversation_id}/finish/', {\n params: { path: { organization: this.orgId, conversation_id: conversationId } },\n headers,\n // No content is expected; parse as text to access raw Response\n parseAs: 'text',\n })\n return\n }\n\n async recommendResponsesForInteraction(\n conversationId: string,\n interactionId: string,\n body?: { context?: string },\n headers?: operations['recommend-responses-for-interaction']['parameters']['header']\n ) {\n return extractData(\n this.c.POST(\n '/v1/{organization}/conversation/{conversation_id}/interaction/{interaction_id}/recommend_responses',\n {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n interaction_id: interactionId,\n },\n },\n body,\n headers,\n }\n )\n )\n }\n\n async getInteractionInsights(\n conversationId: string,\n interactionId: string,\n headers?: operations['get-interaction-insights']['parameters']['header']\n ) {\n return extractData(\n this.c.GET(\n '/v1/{organization}/conversation/{conversation_id}/interaction/{interaction_id}/insights',\n {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n interaction_id: interactionId,\n },\n },\n headers,\n }\n )\n )\n }\n\n // Note: the OpenAPI response schema isn't correct for this endpoint.\n // TODO -- fix response typing.\n async getMessageSource(\n conversationId: string,\n messageId: string,\n headers?: operations['retrieve-message-source']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/{conversation_id}/messages/{message_id}/source', {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n message_id: messageId,\n },\n },\n headers,\n })\n )\n }\n\n async generateConversationStarters(\n body: components['schemas']['conversation__generate_conversation_starter__Request'],\n headers?: operations['generate-conversation-starter']['parameters']['header']\n ) {\n return extractData(\n this.c.POST('/v1/{organization}/conversation/conversation_starter', {\n params: { path: { organization: this.orgId } },\n body,\n headers,\n })\n )\n }\n}\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { operations } from '../generated/api-types'\n\nexport class ServiceResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n /**\n * Get services\n * @param headers - The headers\n * @returns The services\n */\n async getServices(\n queryParams?: operations['get-services']['parameters']['query'],\n headers?: operations['get-services']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/service/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n}\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { components, operations } from '../generated/api-types'\n\nexport class UserResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n async getUsers(\n queryParams?: operations['get-users']['parameters']['query'],\n headers?: operations['get-users']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/user/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n\n async createUser(\n body: components['schemas']['user__create_invited_user__Request'],\n headers?: operations['create-invited-user']['parameters']['header']\n ) {\n return extractData(\n this.c.POST('/v1/{organization}/user/', {\n params: { path: { organization: this.orgId } },\n body,\n headers,\n })\n )\n }\n\n async deleteUser(userId: string, headers?: operations['delete-user']['parameters']['header']) {\n // DELETE endpoints returns no content (e.g., 204 No Content).\n // Our middleware already throws on non-2xx responses, so simply await the call.\n await this.c.DELETE('/v1/{organization}/user/{requested_user_id}', {\n params: { path: { organization: this.orgId, requested_user_id: userId } },\n headers,\n })\n return\n }\n\n async updateUser(\n userId: string,\n body: components['schemas']['user__update_user_info__Request'],\n headers?: operations['update-user-info']['parameters']['header']\n ) {\n // UPDATE endpoint returns no content (e.g., 204 No Content).\n // Our middleware already throws on non-2xx responses, so simply await the call.\n await this.c.POST('/v1/{organization}/user/{requested_user_id}', {\n params: { path: { organization: this.orgId, requested_user_id: userId } },\n body,\n headers,\n })\n return\n }\n\n async getUserModel(\n userId: string,\n headers?: operations['get-user-model']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/user/{user_id}/user_model', {\n params: { path: { organization: this.orgId, user_id: userId } },\n headers,\n })\n )\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,eAAsB,YACpB,iBAC6B;AAC7B,QAAM,SAAS,MAAM;AACrB,QAAM,OAAQ,OAAyC;AAEvD,MAAI,SAAS,UAAa,SAAS,MAAM;AAGvC,UAAM,IAAI,WAAW,+DAA+D,UAAU;AAAA,EAChG;AAEA,SAAO;AACT;AAMA,gBAAuB,kBAA+B,UAAuC;AAC3F,Q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AmB,+BAA+B,OAAO;AAAA,EACrE;AACA,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,UAAU;AAAA,EACnB;AACA,SAAO;AACT;",
6
6
  "names": ["isNetworkError", "createClient"]
7
7
  }
package/dist/index.mjs CHANGED
@@ -519,8 +519,8 @@ var ConversationResource = class {
519
519
  throw new BadRequestError("textMessage is required when request_format is 'text'");
520
520
  }
521
521
  const form = new FormData();
522
- const blob = new Blob([input], { type: "text/plain; charset=utf-8" });
523
- form.append("recorded_message", blob, "message.txt");
522
+ form.append("initial_message_type", "user-message");
523
+ form.append("recorded_message", input);
524
524
  bodyToSend = form;
525
525
  } else if (queryParams.request_format === "voice") {
526
526
  if (typeof input === "string") {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/core/errors.ts", "../src/core/utils.ts", "../src/core/openapi-client.ts", "../src/core/auth.ts", "../src/core/retry.ts", "../src/resources/organization.ts", "../src/resources/conversation.ts", "../src/resources/services.ts", "../src/resources/user.ts", "../src/index.ts"],
4
- "sourcesContent": ["import type { Middleware } from 'openapi-fetch'\nimport { isNetworkError, parseResponseBody } from './utils'\n\n/**\n * Base error class for all Amigo SDK errors.\n * Provides common functionality and error identification.\n */\nexport class AmigoError extends Error {\n /**\n * Unique error code for programmatic error handling\n */\n readonly errorCode?: string\n\n /**\n * HTTP status code if applicable\n */\n readonly statusCode?: number\n\n /**\n * Additional context data\n */\n context?: Record<string, unknown>\n\n constructor(message: string, options?: Record<string, unknown>) {\n super(message)\n this.name = this.constructor.name\n\n // Ensure proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype)\n\n // Capture stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n\n // copies status, code, etc.\n Object.assign(this, options)\n }\n\n /**\n * Returns a JSON-serializable representation of the error\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n code: this.errorCode,\n statusCode: this.statusCode,\n context: this.context,\n stack: this.stack,\n }\n }\n}\n\n/* 4xx client errors */\nexport class BadRequestError extends AmigoError {}\nexport class AuthenticationError extends AmigoError {}\nexport class PermissionError extends AmigoError {}\nexport class NotFoundError extends AmigoError {}\nexport class ConflictError extends AmigoError {}\nexport class RateLimitError extends AmigoError {}\n\n/* 5xx server errors */\nexport class ServerError extends AmigoError {}\nexport class ServiceUnavailableError extends ServerError {}\n\n/* Internal SDK errors */\nexport class ConfigurationError extends AmigoError {\n constructor(\n message: string,\n public field?: string\n ) {\n super(message)\n this.context = { field }\n }\n}\n\n/* Validation errors */\nexport class ValidationError extends BadRequestError {\n constructor(\n msg: string,\n public fieldErrors?: Record<string, string>\n ) {\n super(msg)\n }\n}\n\n/* Network-related errors */\nexport class NetworkError extends AmigoError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n public readonly request?: {\n url?: string\n method?: string\n }\n ) {\n super(message, { cause: originalError })\n this.context = { request }\n }\n}\n\n/* Parsing errors */\nexport class ParseError extends AmigoError {\n constructor(\n message: string,\n public readonly parseType: 'json' | 'response' | 'other',\n public readonly originalError?: Error\n ) {\n super(message, { cause: originalError })\n this.context = { parseType }\n }\n}\n\n/* Type guard functions */\nexport function isAmigoError(error: unknown): error is AmigoError {\n return error instanceof AmigoError\n}\n\n/* Error factory to create appropriate error instances from API responses */\nexport function createApiError(response: Response, body?: unknown): AmigoError {\n const map: Record<number, typeof AmigoError> = {\n 400: BadRequestError,\n 401: AuthenticationError,\n 403: PermissionError,\n 404: NotFoundError,\n 409: ConflictError,\n 422: ValidationError,\n 429: RateLimitError,\n 500: ServerError,\n 503: ServiceUnavailableError,\n }\n\n const errorMessageKeys = ['message', 'error', 'detail']\n\n const ErrorClass = map[response.status] ?? AmigoError\n let message = `HTTP ${response.status} ${response.statusText}`\n\n if (body && typeof body === 'object') {\n for (const key of errorMessageKeys) {\n if (key in body) {\n message = String((body as Record<string, unknown>)[key])\n break\n }\n }\n }\n\n const options = {\n status: response.status,\n code:\n body && typeof body === 'object' && 'code' in body\n ? (body as Record<string, unknown>).code\n : undefined,\n response: body,\n }\n\n const error = new ErrorClass(message, options)\n\n return error\n}\n\nexport function createErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const body = await parseResponseBody(response)\n throw createApiError(response, body)\n }\n },\n onError: async ({ error, request }) => {\n // Handle network-related errors consistently\n if (isNetworkError(error)) {\n throw new NetworkError(\n `Network error: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : new Error(String(error)),\n {\n url: request?.url,\n method: request?.method,\n }\n )\n }\n throw error\n },\n }\n}\n", "import { ParseError } from './errors'\n\n// Type helper to extract the data type from openapi-fetch responses\nexport type ExtractDataType<T> = T extends { data?: infer D } ? NonNullable<D> : never\n\n// Helper function to extract data from openapi-fetch responses\n// Since our middleware throws on errors, successful responses will have data\nexport async function extractData<T extends { data?: unknown }>(\n responsePromise: Promise<T>\n): Promise<ExtractDataType<T>> {\n const result = await responsePromise\n const data = (result as { data?: ExtractDataType<T> }).data\n\n if (data === undefined || data === null) {\n // Invariant: our error middleware throws for non-2xx responses.\n // If we reach here without data, treat as a parse/protocol error.\n throw new ParseError('Expected response data to be present for successful request', 'response')\n }\n\n return data\n}\n\n/**\n * Parse an NDJSON HTTP response body into an async generator of parsed JSON objects.\n * The generator yields one parsed object per line. Empty lines are skipped.\n */\nexport async function* parseNdjsonStream<T = unknown>(response: Response): AsyncGenerator<T> {\n const body = response.body\n if (!body) return\n\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let bufferedText = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n bufferedText += decoder.decode(value, { stream: true })\n\n let newlineIndex: number\n // Process all complete lines in the buffer\n while ((newlineIndex = bufferedText.indexOf('\\n')) !== -1) {\n const line = bufferedText.slice(0, newlineIndex).trim()\n bufferedText = bufferedText.slice(newlineIndex + 1)\n if (!line) continue\n try {\n yield JSON.parse(line) as T\n } catch (err) {\n throw new ParseError('Failed to parse NDJSON line', 'json', err as Error)\n }\n }\n }\n\n // Flush any trailing line without a newline\n const trailing = bufferedText.trim()\n if (trailing) {\n try {\n yield JSON.parse(trailing) as T\n } catch (err) {\n throw new ParseError('Failed to parse trailing NDJSON line', 'json', err as Error)\n }\n }\n } finally {\n reader.releaseLock()\n }\n}\n\n// Utility function to safely parse response bodies without throwing errors\nexport async function parseResponseBody(response: Response): Promise<unknown> {\n try {\n const text = await response.text()\n if (!text) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text // Return as string if not valid JSON\n }\n } catch {\n return undefined // Return undefined if any error occurs\n }\n}\n\n// Helper to detect network-related errors\nexport function isNetworkError(error: unknown): boolean {\n if (!(error instanceof Error)) return false\n\n return (\n error instanceof TypeError ||\n error.message.includes('fetch') ||\n error.message.includes('Failed to fetch') ||\n error.message.includes('Network request failed') ||\n error.message.includes('ECONNREFUSED') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('ENOTFOUND') ||\n error.message.includes('network')\n )\n}\n", "import createClient, { type Client } from 'openapi-fetch'\nimport { createErrorMiddleware } from './errors'\nimport { createAuthMiddleware } from './auth'\nimport type { paths } from '../generated/api-types'\nimport type { AmigoSdkConfig } from '..'\nimport { createRetryingFetch } from './retry'\n\nexport type AmigoFetch = Client<paths>\n\nexport function createAmigoFetch(config: AmigoSdkConfig, mockFetch?: typeof fetch): AmigoFetch {\n const wrappedFetch = createRetryingFetch(\n config.retry,\n mockFetch ?? (globalThis.fetch as typeof fetch)\n )\n\n const client = createClient<paths>({\n baseUrl: config.baseUrl,\n fetch: wrappedFetch,\n })\n\n // Apply error handling middleware first (to catch all errors)\n client.use(createErrorMiddleware())\n\n // Apply auth middleware after error handling (so auth errors are properly handled)\n client.use(createAuthMiddleware(config))\n\n return client\n}\n", "import type { Middleware } from 'openapi-fetch'\nimport type { components } from '../generated/api-types'\nimport type { AmigoSdkConfig } from '..'\nimport { AmigoError, AuthenticationError, NetworkError, ParseError, createApiError } from './errors'\nimport { isNetworkError, parseResponseBody } from './utils'\n\ntype SignInWithApiKeyResponse = components['schemas']['user__sign_in_with_api_key__Response']\n\n/** Helper function to trade API key for a bearer token */\nexport async function getBearerToken(config: AmigoSdkConfig): Promise<SignInWithApiKeyResponse> {\n const url = `${config.baseUrl}/v1/${config.orgId}/user/signin_with_api_key`\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'x-api-key': config.apiKey,\n 'x-api-key-id': config.apiKeyId,\n 'x-user-id': config.userId,\n },\n })\n\n if (!response.ok) {\n const body = await parseResponseBody(response)\n const apiError = createApiError(response, body)\n\n // Enhance authentication errors with additional context\n if (response.status === 401) {\n throw new AuthenticationError(`Authentication failed: ${apiError.message}`, {\n ...apiError,\n context: { ...apiError.context, endpoint: 'signin_with_api_key' },\n })\n }\n throw apiError\n }\n\n return (await response.json()) as SignInWithApiKeyResponse\n } catch (err) {\n // Re-throw our custom errors as-is\n if (err instanceof AmigoError) {\n throw err\n }\n\n // Handle network errors\n if (isNetworkError(err)) {\n throw new NetworkError('Failed to connect to authentication endpoint', err as Error, {\n url,\n method: 'POST',\n })\n }\n\n // Handle JSON parsing errors\n throw new ParseError(\n 'Failed to parse authentication response',\n 'json',\n err instanceof Error ? err : new Error(String(err))\n )\n }\n}\n\nexport function createAuthMiddleware(config: AmigoSdkConfig): Middleware {\n let token: SignInWithApiKeyResponse | null = null\n let refreshPromise: Promise<SignInWithApiKeyResponse> | null = null\n\n const shouldRefreshToken = (tokenData: SignInWithApiKeyResponse): boolean => {\n if (!tokenData.expires_at) return false\n\n const expiryTime = new Date(tokenData.expires_at).getTime()\n const currentTime = Date.now()\n const timeUntilExpiry = expiryTime - currentTime\n const refreshThreshold = 5 * 60 * 1000 // 5 minutes in milliseconds\n\n return timeUntilExpiry <= refreshThreshold\n }\n\n const ensureValidToken = async (): Promise<SignInWithApiKeyResponse> => {\n if (!token || shouldRefreshToken(token)) {\n if (!refreshPromise) {\n refreshPromise = getBearerToken(config)\n try {\n token = await refreshPromise\n } finally {\n refreshPromise = null\n }\n } else {\n token = await refreshPromise\n }\n }\n return token\n }\n\n return {\n onRequest: async ({ request }) => {\n try {\n const validToken = await ensureValidToken()\n if (validToken?.id_token) {\n request.headers.set('Authorization', `Bearer ${validToken.id_token}`)\n }\n } catch (error) {\n // Clear token and re-throw - getBearerToken already provides proper error types\n token = null\n throw error\n }\n return request\n },\n\n onResponse: async ({ response }) => {\n // Handle 401 responses by clearing token to force refresh on next request\n if (response.status === 401) {\n token = null\n }\n },\n\n onError: async ({ error }) => {\n // Clear token on any error to force refresh\n token = null\n throw error\n },\n }\n}\n", "export type RetryOptions = {\n /** Maximum number of attempts to make (default: 3) */\n maxAttempts?: number\n /** Base delay between attempts (default: 250ms) */\n backoffBaseMs?: number\n /** Maximum delay between attempts (default: 30s) */\n maxDelayMs?: number\n /** Status codes to retry on (default: 408, 429, 500, 502, 503, 504) */\n retryOnStatus?: Set<number>\n /** Methods to retry on (default: GET) */\n retryOnMethods?: Set<string>\n}\n\nconst DEFAULT_RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504])\nconst DEFAULT_RETRYABLE_METHODS = new Set(['GET']) as Set<string>\n\nexport function resolveRetryOptions(options?: RetryOptions): Required<RetryOptions> {\n return {\n maxAttempts: options?.maxAttempts ?? 3,\n backoffBaseMs: options?.backoffBaseMs ?? 250,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n retryOnStatus: new Set(options?.retryOnStatus ?? DEFAULT_RETRYABLE_STATUS),\n retryOnMethods: new Set(options?.retryOnMethods ?? DEFAULT_RETRYABLE_METHODS),\n }\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value))\n}\n\nfunction parseRetryAfterMs(headerValue: string | null, maxDelayMs: number): number | null {\n if (!headerValue) return null\n const seconds = Number(headerValue)\n if (Number.isFinite(seconds)) {\n return clamp(seconds * 1000, 0, maxDelayMs)\n }\n const date = new Date(headerValue)\n const ms = date.getTime() - Date.now()\n if (Number.isFinite(ms)) {\n return clamp(ms, 0, maxDelayMs)\n }\n return null\n}\n\nfunction computeBackoffWithJitterMs(\n attemptIndexZeroBased: number,\n baseMs: number,\n capMs: number\n): number {\n const windowMs = Math.min(capMs, baseMs * Math.pow(2, attemptIndexZeroBased))\n return Math.random() * windowMs\n}\n\nfunction isAbortError(err: unknown): boolean {\n return typeof err === 'object' && err !== null && 'name' in err && err['name'] === 'AbortError'\n}\n\nfunction isNetworkError(err: unknown): boolean {\n // Undici & browsers use TypeError for network failures\n return err instanceof TypeError && !isAbortError(err)\n}\n\nasync function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) {\n signal?.throwIfAborted?.()\n return\n }\n await new Promise<void>((resolve, reject) => {\n const rejectWith =\n signal?.reason instanceof Error ? signal.reason : (signal?.reason ?? new Error('AbortError'))\n\n if (signal?.aborted) {\n reject(rejectWith)\n return\n }\n const t = setTimeout(() => {\n off()\n resolve()\n }, ms)\n const onAbort = () => {\n off()\n clearTimeout(t)\n reject(rejectWith)\n }\n const off = () => signal?.removeEventListener('abort', onAbort)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\nexport function createRetryingFetch(\n retryOptions?: RetryOptions,\n baseFetch?: typeof fetch\n): typeof fetch {\n const resolved = resolveRetryOptions(retryOptions)\n const underlying: typeof fetch = baseFetch ?? (globalThis.fetch as typeof fetch)\n\n const retryingFetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> => {\n const inputMethod =\n typeof Request !== 'undefined' && input instanceof Request ? input.method : undefined\n const method = ((init?.method ?? inputMethod ?? 'GET') as string).toUpperCase()\n const signal = init?.signal\n\n const isMethodRetryableByDefault = resolved.retryOnMethods.has(method)\n const maxAttempts = Math.max(1, resolved.maxAttempts)\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n let response: Response | null = null\n let error: unknown = null\n\n try {\n response = await underlying(input, init)\n } catch (err) {\n error = err\n }\n\n if (!error && response && response.ok) {\n return response\n }\n\n let shouldRetry = false\n let delayMs: number | null = null\n\n if (isNetworkError(error)) {\n shouldRetry = isMethodRetryableByDefault\n if (shouldRetry) {\n delayMs = computeBackoffWithJitterMs(\n attempt - 1,\n resolved.backoffBaseMs,\n resolved.maxDelayMs\n )\n }\n } else if (response) {\n const status = response.status\n if (method === 'POST') {\n if (status === 429) {\n const ra = response.headers.get('Retry-After')\n const parsed = parseRetryAfterMs(ra, resolved.maxDelayMs)\n if (parsed !== null) {\n shouldRetry = true\n delayMs = parsed\n }\n }\n } else if (isMethodRetryableByDefault && resolved.retryOnStatus.has(status)) {\n const ra = response.headers.get('Retry-After')\n delayMs =\n parseRetryAfterMs(ra, resolved.maxDelayMs) ??\n computeBackoffWithJitterMs(attempt - 1, resolved.backoffBaseMs, resolved.maxDelayMs)\n shouldRetry = true\n }\n }\n\n const attemptsRemain = attempt < maxAttempts\n if (!shouldRetry || !attemptsRemain) {\n if (error) throw error\n return response as Response\n }\n\n if (signal?.aborted) {\n if (error) throw error\n return response as Response\n }\n\n await abortableSleep(delayMs ?? 0, signal ?? undefined)\n }\n\n throw new Error('Retry loop exited unexpectedly')\n }\n\n return retryingFetch\n}\n\nexport type { RetryOptions as AmigoRetryOptions }\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { operations } from '../generated/api-types'\n\nexport class OrganizationResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n /**\n * Get organization details\n * @param headers - The headers\n * @returns The organization details\n */\n async getOrganization(headers?: operations['get-organization']['parameters']['header']) {\n return extractData(\n this.c.GET('/v1/{organization}/organization/', {\n params: { path: { organization: this.orgId } },\n headers,\n })\n )\n }\n}\n", "import { BadRequestError } from '../core/errors'\nimport type { AmigoFetch } from '../core/openapi-client'\nimport { extractData, parseNdjsonStream } from '../core/utils'\nimport type { components, operations } from '../generated/api-types'\n\ntype VoiceData = Blob | Uint8Array | ReadableStream<Uint8Array>\nexport type InteractionInput = string | VoiceData\n\ntype InteractQuery = operations['interact-with-conversation']['parameters']['query']\ntype InteractQuerySerialized = Omit<InteractQuery, 'request_audio_config'> & {\n request_audio_config?: string | null\n}\n\nexport class ConversationResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n async createConversation(\n body: components['schemas']['conversation__create_conversation__Request'],\n queryParams: operations['create-conversation']['parameters']['query'],\n headers?: operations['create-conversation']['parameters']['header'],\n options?: { signal?: AbortSignal }\n ) {\n const resp = await this.c.POST('/v1/{organization}/conversation/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n body,\n headers: {\n Accept: 'application/x-ndjson',\n ...(headers ?? {}),\n } as operations['create-conversation']['parameters']['header'],\n // Ensure we receive a stream for NDJSON\n parseAs: 'stream',\n ...(options?.signal && { signal: options.signal }),\n })\n\n // onResponse middleware throws for non-2xx; if we reach here, it's OK.\n return parseNdjsonStream<components['schemas']['conversation__create_conversation__Response']>(\n resp.response\n )\n }\n\n async interactWithConversation(\n conversationId: string,\n input: InteractionInput,\n queryParams: operations['interact-with-conversation']['parameters']['query'],\n headers?: operations['interact-with-conversation']['parameters']['header'],\n options?: { signal?: AbortSignal }\n ) {\n // Build body based on requested format, then perform a single POST\n let bodyToSend: FormData | VoiceData\n\n // Prepare headers; we'll merge user-supplied headers and adjust per format\n const mergedHeaders: Record<string, unknown> = {\n Accept: 'application/x-ndjson',\n ...(headers ?? {}),\n }\n\n if (queryParams.request_format === 'text') {\n if (typeof input !== 'string') {\n throw new BadRequestError(\"textMessage is required when request_format is 'text'\")\n }\n const form = new FormData()\n const blob = new Blob([input], { type: 'text/plain; charset=utf-8' })\n form.append('recorded_message', blob, 'message.txt')\n bodyToSend = form\n } else if (queryParams.request_format === 'voice') {\n if (typeof input === 'string') {\n throw new BadRequestError(\n \"voice input must be a byte source when request_format is 'voice'\"\n )\n }\n bodyToSend = input\n } else {\n throw new BadRequestError('Unsupported or missing request_format in params')\n }\n\n // For text/FormData, do NOT set Content-Type; fetch will set multipart boundary\n if (queryParams.request_format === 'text') {\n delete mergedHeaders['content-type']\n delete mergedHeaders['Content-Type']\n }\n\n // For voice bytes, allow caller to specify Content-Type; if absent and input is a Blob with a type, use it\n if (queryParams.request_format === 'voice') {\n const hasContentType =\n mergedHeaders['content-type'] !== undefined || mergedHeaders['Content-Type'] !== undefined\n if (!hasContentType && typeof Blob !== 'undefined' && input instanceof Blob && input.type) {\n mergedHeaders['content-type'] = input.type\n }\n }\n\n const headersToSend =\n mergedHeaders as unknown as operations['interact-with-conversation']['parameters']['header']\n\n // Normalize nested object params that must be sent as JSON strings\n const normalizedQuery: InteractQuerySerialized = {\n ...queryParams,\n request_audio_config:\n typeof queryParams.request_audio_config === 'object' &&\n queryParams.request_audio_config !== null\n ? JSON.stringify(queryParams.request_audio_config)\n : (queryParams.request_audio_config ?? undefined),\n }\n\n const resp = await this.c.POST('/v1/{organization}/conversation/{conversation_id}/interact', {\n params: {\n path: { organization: this.orgId, conversation_id: conversationId },\n query: normalizedQuery as unknown as InteractQuery,\n header: headersToSend,\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body: bodyToSend as any, // FormData/Blob not represented in generated OpenAPI types\n parseAs: 'stream',\n ...(options?.signal && { signal: options.signal }),\n })\n\n return parseNdjsonStream<\n components['schemas']['conversation__interact_with_conversation__Response']\n >(resp.response)\n }\n\n async getConversations(\n queryParams?: operations['get-conversations']['parameters']['query'],\n headers?: operations['get-conversations']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n\n async getConversationMessages(\n conversationId: string,\n queryParams?: operations['get-conversation-messages']['parameters']['query'],\n headers?: operations['get-conversation-messages']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/{conversation_id}/messages/', {\n params: {\n path: { organization: this.orgId, conversation_id: conversationId },\n query: queryParams,\n },\n headers,\n })\n )\n }\n\n async finishConversation(\n conversationId: string,\n headers?: operations['finish-conversation']['parameters']['header']\n ) {\n await this.c.POST('/v1/{organization}/conversation/{conversation_id}/finish/', {\n params: { path: { organization: this.orgId, conversation_id: conversationId } },\n headers,\n // No content is expected; parse as text to access raw Response\n parseAs: 'text',\n })\n return\n }\n\n async recommendResponsesForInteraction(\n conversationId: string,\n interactionId: string,\n body?: { context?: string },\n headers?: operations['recommend-responses-for-interaction']['parameters']['header']\n ) {\n return extractData(\n this.c.POST(\n '/v1/{organization}/conversation/{conversation_id}/interaction/{interaction_id}/recommend_responses',\n {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n interaction_id: interactionId,\n },\n },\n body,\n headers,\n }\n )\n )\n }\n\n async getInteractionInsights(\n conversationId: string,\n interactionId: string,\n headers?: operations['get-interaction-insights']['parameters']['header']\n ) {\n return extractData(\n this.c.GET(\n '/v1/{organization}/conversation/{conversation_id}/interaction/{interaction_id}/insights',\n {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n interaction_id: interactionId,\n },\n },\n headers,\n }\n )\n )\n }\n\n // Note: the OpenAPI response schema isn't correct for this endpoint.\n // TODO -- fix response typing.\n async getMessageSource(\n conversationId: string,\n messageId: string,\n headers?: operations['retrieve-message-source']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/{conversation_id}/messages/{message_id}/source', {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n message_id: messageId,\n },\n },\n headers,\n })\n )\n }\n\n async generateConversationStarters(\n body: components['schemas']['conversation__generate_conversation_starter__Request'],\n headers?: operations['generate-conversation-starter']['parameters']['header']\n ) {\n return extractData(\n this.c.POST('/v1/{organization}/conversation/conversation_starter', {\n params: { path: { organization: this.orgId } },\n body,\n headers,\n })\n )\n }\n}\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { operations } from '../generated/api-types'\n\nexport class ServiceResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n /**\n * Get services\n * @param headers - The headers\n * @returns The services\n */\n async getServices(\n queryParams?: operations['get-services']['parameters']['query'],\n headers?: operations['get-services']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/service/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n}\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { components, operations } from '../generated/api-types'\n\nexport class UserResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n async getUsers(\n queryParams?: operations['get-users']['parameters']['query'],\n headers?: operations['get-users']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/user/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n\n async createUser(\n body: components['schemas']['user__create_invited_user__Request'],\n headers?: operations['create-invited-user']['parameters']['header']\n ) {\n return extractData(\n this.c.POST('/v1/{organization}/user/', {\n params: { path: { organization: this.orgId } },\n body,\n headers,\n })\n )\n }\n\n async deleteUser(userId: string, headers?: operations['delete-user']['parameters']['header']) {\n // DELETE endpoints returns no content (e.g., 204 No Content).\n // Our middleware already throws on non-2xx responses, so simply await the call.\n await this.c.DELETE('/v1/{organization}/user/{requested_user_id}', {\n params: { path: { organization: this.orgId, requested_user_id: userId } },\n headers,\n })\n return\n }\n\n async updateUser(\n userId: string,\n body: components['schemas']['user__update_user_info__Request'],\n headers?: operations['update-user-info']['parameters']['header']\n ) {\n // UPDATE endpoint returns no content (e.g., 204 No Content).\n // Our middleware already throws on non-2xx responses, so simply await the call.\n await this.c.POST('/v1/{organization}/user/{requested_user_id}', {\n params: { path: { organization: this.orgId, requested_user_id: userId } },\n body,\n headers,\n })\n return\n }\n\n async getUserModel(\n userId: string,\n headers?: operations['get-user-model']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/user/{user_id}/user_model', {\n params: { path: { organization: this.orgId, user_id: userId } },\n headers,\n })\n )\n }\n}\n", "import { ConfigurationError } from './core/errors'\nimport { createAmigoFetch } from './core/openapi-client'\nimport { OrganizationResource } from './resources/organization'\nimport { ConversationResource } from './resources/conversation'\nimport { ServiceResource } from './resources/services'\nimport { UserResource } from './resources/user'\nimport type { RetryOptions } from './core/retry'\n\nexport interface AmigoSdkConfig {\n /** API key from Amigo dashboard */\n apiKey: string\n /** API-key ID from Amigo dashboard */\n apiKeyId: string\n /** User ID on whose behalf the request is made */\n userId: string\n /** The Organization ID */\n orgId: string\n /** Base URL of the Amigo API */\n baseUrl?: string\n /** Retry configuration for HTTP requests */\n retry?: RetryOptions\n}\n\nconst defaultBaseUrl = 'https://api.amigo.ai'\n\nexport class AmigoClient {\n readonly organizations: OrganizationResource\n readonly conversations: ConversationResource\n readonly services: ServiceResource\n readonly users: UserResource\n readonly config: AmigoSdkConfig\n\n constructor(config: AmigoSdkConfig) {\n this.config = validateConfig(config)\n\n const api = createAmigoFetch(this.config)\n this.organizations = new OrganizationResource(api, this.config.orgId)\n this.conversations = new ConversationResource(api, this.config.orgId)\n this.services = new ServiceResource(api, this.config.orgId)\n this.users = new UserResource(api, this.config.orgId)\n }\n}\n\nfunction validateConfig(config: AmigoSdkConfig) {\n if (!config.apiKey) {\n throw new ConfigurationError('API key is required', 'apiKey')\n }\n if (!config.apiKeyId) {\n throw new ConfigurationError('API key ID is required', 'apiKeyId')\n }\n if (!config.userId) {\n throw new ConfigurationError('User ID is required', 'userId')\n }\n if (!config.orgId) {\n throw new ConfigurationError('Organization ID is required', 'orgId')\n }\n if (!config.baseUrl) {\n config.baseUrl = defaultBaseUrl\n }\n return config\n}\n\n// Export all errors as a namespace to avoid polluting the main import space\nexport * as errors from './core/errors'\n\n// Re-export useful types for consumers\nexport type { components, operations, paths } from './generated/api-types'\n"],
5
- "mappings": ";;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,eAAsB,YACpB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AmB,uBAAuB,QAAQ;AAAA,EAC9D;AACA,MAAI,CAAC,OAAO,UAAU;AACpB,UAAM,IAAI,mBAAmB,0BAA0B,UAAU;AAAA,EACnE;AACA,MAAI,CAAC,OAAO,QAAQ;AAClB,UAAM,IAAI,mBAAmB,uBAAuB,QAAQ;AAAA,EAC9D;AACA,MAAI,CAAC,OAAO,OAAO;AACjB,UAAM,IAAI,mBAAmB,+BAA+B,OAAO;AAAA,EACrE;AACA,MAAI,CAAC,OAAO,SAAS;AACnB,WAAO,UAAU;AAAA,EACnB;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import type { Middleware } from 'openapi-fetch'\nimport { isNetworkError, parseResponseBody } from './utils'\n\n/**\n * Base error class for all Amigo SDK errors.\n * Provides common functionality and error identification.\n */\nexport class AmigoError extends Error {\n /**\n * Unique error code for programmatic error handling\n */\n readonly errorCode?: string\n\n /**\n * HTTP status code if applicable\n */\n readonly statusCode?: number\n\n /**\n * Additional context data\n */\n context?: Record<string, unknown>\n\n constructor(message: string, options?: Record<string, unknown>) {\n super(message)\n this.name = this.constructor.name\n\n // Ensure proper prototype chain for instanceof checks\n Object.setPrototypeOf(this, new.target.prototype)\n\n // Capture stack trace\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n\n // copies status, code, etc.\n Object.assign(this, options)\n }\n\n /**\n * Returns a JSON-serializable representation of the error\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n message: this.message,\n code: this.errorCode,\n statusCode: this.statusCode,\n context: this.context,\n stack: this.stack,\n }\n }\n}\n\n/* 4xx client errors */\nexport class BadRequestError extends AmigoError {}\nexport class AuthenticationError extends AmigoError {}\nexport class PermissionError extends AmigoError {}\nexport class NotFoundError extends AmigoError {}\nexport class ConflictError extends AmigoError {}\nexport class RateLimitError extends AmigoError {}\n\n/* 5xx server errors */\nexport class ServerError extends AmigoError {}\nexport class ServiceUnavailableError extends ServerError {}\n\n/* Internal SDK errors */\nexport class ConfigurationError extends AmigoError {\n constructor(\n message: string,\n public field?: string\n ) {\n super(message)\n this.context = { field }\n }\n}\n\n/* Validation errors */\nexport class ValidationError extends BadRequestError {\n constructor(\n msg: string,\n public fieldErrors?: Record<string, string>\n ) {\n super(msg)\n }\n}\n\n/* Network-related errors */\nexport class NetworkError extends AmigoError {\n constructor(\n message: string,\n public readonly originalError?: Error,\n public readonly request?: {\n url?: string\n method?: string\n }\n ) {\n super(message, { cause: originalError })\n this.context = { request }\n }\n}\n\n/* Parsing errors */\nexport class ParseError extends AmigoError {\n constructor(\n message: string,\n public readonly parseType: 'json' | 'response' | 'other',\n public readonly originalError?: Error\n ) {\n super(message, { cause: originalError })\n this.context = { parseType }\n }\n}\n\n/* Type guard functions */\nexport function isAmigoError(error: unknown): error is AmigoError {\n return error instanceof AmigoError\n}\n\n/* Error factory to create appropriate error instances from API responses */\nexport function createApiError(response: Response, body?: unknown): AmigoError {\n const map: Record<number, typeof AmigoError> = {\n 400: BadRequestError,\n 401: AuthenticationError,\n 403: PermissionError,\n 404: NotFoundError,\n 409: ConflictError,\n 422: ValidationError,\n 429: RateLimitError,\n 500: ServerError,\n 503: ServiceUnavailableError,\n }\n\n const errorMessageKeys = ['message', 'error', 'detail']\n\n const ErrorClass = map[response.status] ?? AmigoError\n let message = `HTTP ${response.status} ${response.statusText}`\n\n if (body && typeof body === 'object') {\n for (const key of errorMessageKeys) {\n if (key in body) {\n message = String((body as Record<string, unknown>)[key])\n break\n }\n }\n }\n\n const options = {\n status: response.status,\n code:\n body && typeof body === 'object' && 'code' in body\n ? (body as Record<string, unknown>).code\n : undefined,\n response: body,\n }\n\n const error = new ErrorClass(message, options)\n\n return error\n}\n\nexport function createErrorMiddleware(): Middleware {\n return {\n onResponse: async ({ response }) => {\n if (!response.ok) {\n const body = await parseResponseBody(response)\n throw createApiError(response, body)\n }\n },\n onError: async ({ error, request }) => {\n // Handle network-related errors consistently\n if (isNetworkError(error)) {\n throw new NetworkError(\n `Network error: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : new Error(String(error)),\n {\n url: request?.url,\n method: request?.method,\n }\n )\n }\n throw error\n },\n }\n}\n", "import { ParseError } from './errors'\n\n// Type helper to extract the data type from openapi-fetch responses\nexport type ExtractDataType<T> = T extends { data?: infer D } ? NonNullable<D> : never\n\n// Helper function to extract data from openapi-fetch responses\n// Since our middleware throws on errors, successful responses will have data\nexport async function extractData<T extends { data?: unknown }>(\n responsePromise: Promise<T>\n): Promise<ExtractDataType<T>> {\n const result = await responsePromise\n const data = (result as { data?: ExtractDataType<T> }).data\n\n if (data === undefined || data === null) {\n // Invariant: our error middleware throws for non-2xx responses.\n // If we reach here without data, treat as a parse/protocol error.\n throw new ParseError('Expected response data to be present for successful request', 'response')\n }\n\n return data\n}\n\n/**\n * Parse an NDJSON HTTP response body into an async generator of parsed JSON objects.\n * The generator yields one parsed object per line. Empty lines are skipped.\n */\nexport async function* parseNdjsonStream<T = unknown>(response: Response): AsyncGenerator<T> {\n const body = response.body\n if (!body) return\n\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let bufferedText = ''\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n bufferedText += decoder.decode(value, { stream: true })\n\n let newlineIndex: number\n // Process all complete lines in the buffer\n while ((newlineIndex = bufferedText.indexOf('\\n')) !== -1) {\n const line = bufferedText.slice(0, newlineIndex).trim()\n bufferedText = bufferedText.slice(newlineIndex + 1)\n if (!line) continue\n try {\n yield JSON.parse(line) as T\n } catch (err) {\n throw new ParseError('Failed to parse NDJSON line', 'json', err as Error)\n }\n }\n }\n\n // Flush any trailing line without a newline\n const trailing = bufferedText.trim()\n if (trailing) {\n try {\n yield JSON.parse(trailing) as T\n } catch (err) {\n throw new ParseError('Failed to parse trailing NDJSON line', 'json', err as Error)\n }\n }\n } finally {\n reader.releaseLock()\n }\n}\n\n// Utility function to safely parse response bodies without throwing errors\nexport async function parseResponseBody(response: Response): Promise<unknown> {\n try {\n const text = await response.text()\n if (!text) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text // Return as string if not valid JSON\n }\n } catch {\n return undefined // Return undefined if any error occurs\n }\n}\n\n// Helper to detect network-related errors\nexport function isNetworkError(error: unknown): boolean {\n if (!(error instanceof Error)) return false\n\n return (\n error instanceof TypeError ||\n error.message.includes('fetch') ||\n error.message.includes('Failed to fetch') ||\n error.message.includes('Network request failed') ||\n error.message.includes('ECONNREFUSED') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('ENOTFOUND') ||\n error.message.includes('network')\n )\n}\n", "import createClient, { type Client } from 'openapi-fetch'\nimport { createErrorMiddleware } from './errors'\nimport { createAuthMiddleware } from './auth'\nimport type { paths } from '../generated/api-types'\nimport type { AmigoSdkConfig } from '..'\nimport { createRetryingFetch } from './retry'\n\nexport type AmigoFetch = Client<paths>\n\nexport function createAmigoFetch(config: AmigoSdkConfig, mockFetch?: typeof fetch): AmigoFetch {\n const wrappedFetch = createRetryingFetch(\n config.retry,\n mockFetch ?? (globalThis.fetch as typeof fetch)\n )\n\n const client = createClient<paths>({\n baseUrl: config.baseUrl,\n fetch: wrappedFetch,\n })\n\n // Apply error handling middleware first (to catch all errors)\n client.use(createErrorMiddleware())\n\n // Apply auth middleware after error handling (so auth errors are properly handled)\n client.use(createAuthMiddleware(config))\n\n return client\n}\n", "import type { Middleware } from 'openapi-fetch'\nimport type { components } from '../generated/api-types'\nimport type { AmigoSdkConfig } from '..'\nimport { AmigoError, AuthenticationError, NetworkError, ParseError, createApiError } from './errors'\nimport { isNetworkError, parseResponseBody } from './utils'\n\ntype SignInWithApiKeyResponse = components['schemas']['user__sign_in_with_api_key__Response']\n\n/** Helper function to trade API key for a bearer token */\nexport async function getBearerToken(config: AmigoSdkConfig): Promise<SignInWithApiKeyResponse> {\n const url = `${config.baseUrl}/v1/${config.orgId}/user/signin_with_api_key`\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'x-api-key': config.apiKey,\n 'x-api-key-id': config.apiKeyId,\n 'x-user-id': config.userId,\n },\n })\n\n if (!response.ok) {\n const body = await parseResponseBody(response)\n const apiError = createApiError(response, body)\n\n // Enhance authentication errors with additional context\n if (response.status === 401) {\n throw new AuthenticationError(`Authentication failed: ${apiError.message}`, {\n ...apiError,\n context: { ...apiError.context, endpoint: 'signin_with_api_key' },\n })\n }\n throw apiError\n }\n\n return (await response.json()) as SignInWithApiKeyResponse\n } catch (err) {\n // Re-throw our custom errors as-is\n if (err instanceof AmigoError) {\n throw err\n }\n\n // Handle network errors\n if (isNetworkError(err)) {\n throw new NetworkError('Failed to connect to authentication endpoint', err as Error, {\n url,\n method: 'POST',\n })\n }\n\n // Handle JSON parsing errors\n throw new ParseError(\n 'Failed to parse authentication response',\n 'json',\n err instanceof Error ? err : new Error(String(err))\n )\n }\n}\n\nexport function createAuthMiddleware(config: AmigoSdkConfig): Middleware {\n let token: SignInWithApiKeyResponse | null = null\n let refreshPromise: Promise<SignInWithApiKeyResponse> | null = null\n\n const shouldRefreshToken = (tokenData: SignInWithApiKeyResponse): boolean => {\n if (!tokenData.expires_at) return false\n\n const expiryTime = new Date(tokenData.expires_at).getTime()\n const currentTime = Date.now()\n const timeUntilExpiry = expiryTime - currentTime\n const refreshThreshold = 5 * 60 * 1000 // 5 minutes in milliseconds\n\n return timeUntilExpiry <= refreshThreshold\n }\n\n const ensureValidToken = async (): Promise<SignInWithApiKeyResponse> => {\n if (!token || shouldRefreshToken(token)) {\n if (!refreshPromise) {\n refreshPromise = getBearerToken(config)\n try {\n token = await refreshPromise\n } finally {\n refreshPromise = null\n }\n } else {\n token = await refreshPromise\n }\n }\n return token\n }\n\n return {\n onRequest: async ({ request }) => {\n try {\n const validToken = await ensureValidToken()\n if (validToken?.id_token) {\n request.headers.set('Authorization', `Bearer ${validToken.id_token}`)\n }\n } catch (error) {\n // Clear token and re-throw - getBearerToken already provides proper error types\n token = null\n throw error\n }\n return request\n },\n\n onResponse: async ({ response }) => {\n // Handle 401 responses by clearing token to force refresh on next request\n if (response.status === 401) {\n token = null\n }\n },\n\n onError: async ({ error }) => {\n // Clear token on any error to force refresh\n token = null\n throw error\n },\n }\n}\n", "export type RetryOptions = {\n /** Maximum number of attempts to make (default: 3) */\n maxAttempts?: number\n /** Base delay between attempts (default: 250ms) */\n backoffBaseMs?: number\n /** Maximum delay between attempts (default: 30s) */\n maxDelayMs?: number\n /** Status codes to retry on (default: 408, 429, 500, 502, 503, 504) */\n retryOnStatus?: Set<number>\n /** Methods to retry on (default: GET) */\n retryOnMethods?: Set<string>\n}\n\nconst DEFAULT_RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504])\nconst DEFAULT_RETRYABLE_METHODS = new Set(['GET']) as Set<string>\n\nexport function resolveRetryOptions(options?: RetryOptions): Required<RetryOptions> {\n return {\n maxAttempts: options?.maxAttempts ?? 3,\n backoffBaseMs: options?.backoffBaseMs ?? 250,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n retryOnStatus: new Set(options?.retryOnStatus ?? DEFAULT_RETRYABLE_STATUS),\n retryOnMethods: new Set(options?.retryOnMethods ?? DEFAULT_RETRYABLE_METHODS),\n }\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value))\n}\n\nfunction parseRetryAfterMs(headerValue: string | null, maxDelayMs: number): number | null {\n if (!headerValue) return null\n const seconds = Number(headerValue)\n if (Number.isFinite(seconds)) {\n return clamp(seconds * 1000, 0, maxDelayMs)\n }\n const date = new Date(headerValue)\n const ms = date.getTime() - Date.now()\n if (Number.isFinite(ms)) {\n return clamp(ms, 0, maxDelayMs)\n }\n return null\n}\n\nfunction computeBackoffWithJitterMs(\n attemptIndexZeroBased: number,\n baseMs: number,\n capMs: number\n): number {\n const windowMs = Math.min(capMs, baseMs * Math.pow(2, attemptIndexZeroBased))\n return Math.random() * windowMs\n}\n\nfunction isAbortError(err: unknown): boolean {\n return typeof err === 'object' && err !== null && 'name' in err && err['name'] === 'AbortError'\n}\n\nfunction isNetworkError(err: unknown): boolean {\n // Undici & browsers use TypeError for network failures\n return err instanceof TypeError && !isAbortError(err)\n}\n\nasync function abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) {\n signal?.throwIfAborted?.()\n return\n }\n await new Promise<void>((resolve, reject) => {\n const rejectWith =\n signal?.reason instanceof Error ? signal.reason : (signal?.reason ?? new Error('AbortError'))\n\n if (signal?.aborted) {\n reject(rejectWith)\n return\n }\n const t = setTimeout(() => {\n off()\n resolve()\n }, ms)\n const onAbort = () => {\n off()\n clearTimeout(t)\n reject(rejectWith)\n }\n const off = () => signal?.removeEventListener('abort', onAbort)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n}\n\nexport function createRetryingFetch(\n retryOptions?: RetryOptions,\n baseFetch?: typeof fetch\n): typeof fetch {\n const resolved = resolveRetryOptions(retryOptions)\n const underlying: typeof fetch = baseFetch ?? (globalThis.fetch as typeof fetch)\n\n const retryingFetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit\n ): Promise<Response> => {\n const inputMethod =\n typeof Request !== 'undefined' && input instanceof Request ? input.method : undefined\n const method = ((init?.method ?? inputMethod ?? 'GET') as string).toUpperCase()\n const signal = init?.signal\n\n const isMethodRetryableByDefault = resolved.retryOnMethods.has(method)\n const maxAttempts = Math.max(1, resolved.maxAttempts)\n\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n let response: Response | null = null\n let error: unknown = null\n\n try {\n response = await underlying(input, init)\n } catch (err) {\n error = err\n }\n\n if (!error && response && response.ok) {\n return response\n }\n\n let shouldRetry = false\n let delayMs: number | null = null\n\n if (isNetworkError(error)) {\n shouldRetry = isMethodRetryableByDefault\n if (shouldRetry) {\n delayMs = computeBackoffWithJitterMs(\n attempt - 1,\n resolved.backoffBaseMs,\n resolved.maxDelayMs\n )\n }\n } else if (response) {\n const status = response.status\n if (method === 'POST') {\n if (status === 429) {\n const ra = response.headers.get('Retry-After')\n const parsed = parseRetryAfterMs(ra, resolved.maxDelayMs)\n if (parsed !== null) {\n shouldRetry = true\n delayMs = parsed\n }\n }\n } else if (isMethodRetryableByDefault && resolved.retryOnStatus.has(status)) {\n const ra = response.headers.get('Retry-After')\n delayMs =\n parseRetryAfterMs(ra, resolved.maxDelayMs) ??\n computeBackoffWithJitterMs(attempt - 1, resolved.backoffBaseMs, resolved.maxDelayMs)\n shouldRetry = true\n }\n }\n\n const attemptsRemain = attempt < maxAttempts\n if (!shouldRetry || !attemptsRemain) {\n if (error) throw error\n return response as Response\n }\n\n if (signal?.aborted) {\n if (error) throw error\n return response as Response\n }\n\n await abortableSleep(delayMs ?? 0, signal ?? undefined)\n }\n\n throw new Error('Retry loop exited unexpectedly')\n }\n\n return retryingFetch\n}\n\nexport type { RetryOptions as AmigoRetryOptions }\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { operations } from '../generated/api-types'\n\nexport class OrganizationResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n /**\n * Get organization details\n * @param headers - The headers\n * @returns The organization details\n */\n async getOrganization(headers?: operations['get-organization']['parameters']['header']) {\n return extractData(\n this.c.GET('/v1/{organization}/organization/', {\n params: { path: { organization: this.orgId } },\n headers,\n })\n )\n }\n}\n", "import { BadRequestError } from '../core/errors'\nimport type { AmigoFetch } from '../core/openapi-client'\nimport { extractData, parseNdjsonStream } from '../core/utils'\nimport type { components, operations } from '../generated/api-types'\n\ntype VoiceData = Blob | Uint8Array | ReadableStream<Uint8Array>\nexport type InteractionInput = string | VoiceData\n\ntype InteractQuery = operations['interact-with-conversation']['parameters']['query']\ntype InteractQuerySerialized = Omit<InteractQuery, 'request_audio_config'> & {\n request_audio_config?: string | null\n}\n\nexport class ConversationResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n async createConversation(\n body: components['schemas']['conversation__create_conversation__Request'],\n queryParams: operations['create-conversation']['parameters']['query'],\n headers?: operations['create-conversation']['parameters']['header'],\n options?: { signal?: AbortSignal }\n ) {\n const resp = await this.c.POST('/v1/{organization}/conversation/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n body,\n headers: {\n Accept: 'application/x-ndjson',\n ...(headers ?? {}),\n } as operations['create-conversation']['parameters']['header'],\n // Ensure we receive a stream for NDJSON\n parseAs: 'stream',\n ...(options?.signal && { signal: options.signal }),\n })\n\n // onResponse middleware throws for non-2xx; if we reach here, it's OK.\n return parseNdjsonStream<components['schemas']['conversation__create_conversation__Response']>(\n resp.response\n )\n }\n\n async interactWithConversation(\n conversationId: string,\n input: InteractionInput,\n queryParams: operations['interact-with-conversation']['parameters']['query'],\n headers?: operations['interact-with-conversation']['parameters']['header'],\n options?: { signal?: AbortSignal }\n ) {\n // Build body based on requested format, then perform a single POST\n let bodyToSend: FormData | VoiceData\n\n // Prepare headers; we'll merge user-supplied headers and adjust per format\n const mergedHeaders: Record<string, unknown> = {\n Accept: 'application/x-ndjson',\n ...(headers ?? {}),\n }\n\n if (queryParams.request_format === 'text') {\n if (typeof input !== 'string') {\n throw new BadRequestError(\"textMessage is required when request_format is 'text'\")\n }\n const form = new FormData()\n form.append('initial_message_type', 'user-message')\n form.append('recorded_message', input)\n bodyToSend = form\n } else if (queryParams.request_format === 'voice') {\n if (typeof input === 'string') {\n throw new BadRequestError(\n \"voice input must be a byte source when request_format is 'voice'\"\n )\n }\n bodyToSend = input\n } else {\n throw new BadRequestError('Unsupported or missing request_format in params')\n }\n\n // For text/FormData, do NOT set Content-Type; fetch will set multipart boundary\n if (queryParams.request_format === 'text') {\n delete mergedHeaders['content-type']\n delete mergedHeaders['Content-Type']\n }\n\n // For voice bytes, allow caller to specify Content-Type; if absent and input is a Blob with a type, use it\n if (queryParams.request_format === 'voice') {\n const hasContentType =\n mergedHeaders['content-type'] !== undefined || mergedHeaders['Content-Type'] !== undefined\n if (!hasContentType && typeof Blob !== 'undefined' && input instanceof Blob && input.type) {\n mergedHeaders['content-type'] = input.type\n }\n }\n\n const headersToSend =\n mergedHeaders as unknown as operations['interact-with-conversation']['parameters']['header']\n\n // Normalize nested object params that must be sent as JSON strings\n const normalizedQuery: InteractQuerySerialized = {\n ...queryParams,\n request_audio_config:\n typeof queryParams.request_audio_config === 'object' &&\n queryParams.request_audio_config !== null\n ? JSON.stringify(queryParams.request_audio_config)\n : (queryParams.request_audio_config ?? undefined),\n }\n\n const resp = await this.c.POST('/v1/{organization}/conversation/{conversation_id}/interact', {\n params: {\n path: { organization: this.orgId, conversation_id: conversationId },\n query: normalizedQuery as unknown as InteractQuery,\n header: headersToSend,\n },\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n body: bodyToSend as any, // FormData/Blob not represented in generated OpenAPI types\n parseAs: 'stream',\n ...(options?.signal && { signal: options.signal }),\n })\n\n return parseNdjsonStream<\n components['schemas']['conversation__interact_with_conversation__Response']\n >(resp.response)\n }\n\n async getConversations(\n queryParams?: operations['get-conversations']['parameters']['query'],\n headers?: operations['get-conversations']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n\n async getConversationMessages(\n conversationId: string,\n queryParams?: operations['get-conversation-messages']['parameters']['query'],\n headers?: operations['get-conversation-messages']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/{conversation_id}/messages/', {\n params: {\n path: { organization: this.orgId, conversation_id: conversationId },\n query: queryParams,\n },\n headers,\n })\n )\n }\n\n async finishConversation(\n conversationId: string,\n headers?: operations['finish-conversation']['parameters']['header']\n ) {\n await this.c.POST('/v1/{organization}/conversation/{conversation_id}/finish/', {\n params: { path: { organization: this.orgId, conversation_id: conversationId } },\n headers,\n // No content is expected; parse as text to access raw Response\n parseAs: 'text',\n })\n return\n }\n\n async recommendResponsesForInteraction(\n conversationId: string,\n interactionId: string,\n body?: { context?: string },\n headers?: operations['recommend-responses-for-interaction']['parameters']['header']\n ) {\n return extractData(\n this.c.POST(\n '/v1/{organization}/conversation/{conversation_id}/interaction/{interaction_id}/recommend_responses',\n {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n interaction_id: interactionId,\n },\n },\n body,\n headers,\n }\n )\n )\n }\n\n async getInteractionInsights(\n conversationId: string,\n interactionId: string,\n headers?: operations['get-interaction-insights']['parameters']['header']\n ) {\n return extractData(\n this.c.GET(\n '/v1/{organization}/conversation/{conversation_id}/interaction/{interaction_id}/insights',\n {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n interaction_id: interactionId,\n },\n },\n headers,\n }\n )\n )\n }\n\n // Note: the OpenAPI response schema isn't correct for this endpoint.\n // TODO -- fix response typing.\n async getMessageSource(\n conversationId: string,\n messageId: string,\n headers?: operations['retrieve-message-source']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/conversation/{conversation_id}/messages/{message_id}/source', {\n params: {\n path: {\n organization: this.orgId,\n conversation_id: conversationId,\n message_id: messageId,\n },\n },\n headers,\n })\n )\n }\n\n async generateConversationStarters(\n body: components['schemas']['conversation__generate_conversation_starter__Request'],\n headers?: operations['generate-conversation-starter']['parameters']['header']\n ) {\n return extractData(\n this.c.POST('/v1/{organization}/conversation/conversation_starter', {\n params: { path: { organization: this.orgId } },\n body,\n headers,\n })\n )\n }\n}\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { operations } from '../generated/api-types'\n\nexport class ServiceResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n /**\n * Get services\n * @param headers - The headers\n * @returns The services\n */\n async getServices(\n queryParams?: operations['get-services']['parameters']['query'],\n headers?: operations['get-services']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/service/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n}\n", "import type { AmigoFetch } from '../core/openapi-client'\nimport { extractData } from '../core/utils'\nimport type { components, operations } from '../generated/api-types'\n\nexport class UserResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n async getUsers(\n queryParams?: operations['get-users']['parameters']['query'],\n headers?: operations['get-users']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/user/', {\n params: { path: { organization: this.orgId }, query: queryParams },\n headers,\n })\n )\n }\n\n async createUser(\n body: components['schemas']['user__create_invited_user__Request'],\n headers?: operations['create-invited-user']['parameters']['header']\n ) {\n return extractData(\n this.c.POST('/v1/{organization}/user/', {\n params: { path: { organization: this.orgId } },\n body,\n headers,\n })\n )\n }\n\n async deleteUser(userId: string, headers?: operations['delete-user']['parameters']['header']) {\n // DELETE endpoints returns no content (e.g., 204 No Content).\n // Our middleware already throws on non-2xx responses, so simply await the call.\n await this.c.DELETE('/v1/{organization}/user/{requested_user_id}', {\n params: { path: { organization: this.orgId, requested_user_id: userId } },\n headers,\n })\n return\n }\n\n async updateUser(\n userId: string,\n body: components['schemas']['user__update_user_info__Request'],\n headers?: operations['update-user-info']['parameters']['header']\n ) {\n // UPDATE endpoint returns no content (e.g., 204 No Content).\n // Our middleware already throws on non-2xx responses, so simply await the call.\n await this.c.POST('/v1/{organization}/user/{requested_user_id}', {\n params: { path: { organization: this.orgId, requested_user_id: userId } },\n body,\n headers,\n })\n return\n }\n\n async getUserModel(\n userId: string,\n headers?: operations['get-user-model']['parameters']['header']\n ) {\n return extractData(\n this.c.GET('/v1/{organization}/user/{user_id}/user_model', {\n params: { path: { organization: this.orgId, user_id: userId } },\n headers,\n })\n )\n }\n}\n", "import { ConfigurationError } from './core/errors'\nimport { createAmigoFetch } from './core/openapi-client'\nimport { OrganizationResource } from './resources/organization'\nimport { ConversationResource } from './resources/conversation'\nimport { ServiceResource } from './resources/services'\nimport { UserResource } from './resources/user'\nimport type { RetryOptions } from './core/retry'\n\nexport interface AmigoSdkConfig {\n /** API key from Amigo dashboard */\n apiKey: string\n /** API-key ID from Amigo dashboard */\n apiKeyId: string\n /** User ID on whose behalf the request is made */\n userId: string\n /** The Organization ID */\n orgId: string\n /** Base URL of the Amigo API */\n baseUrl?: string\n /** Retry configuration for HTTP requests */\n retry?: RetryOptions\n}\n\nconst defaultBaseUrl = 'https://api.amigo.ai'\n\nexport class AmigoClient {\n readonly organizations: OrganizationResource\n readonly conversations: ConversationResource\n readonly services: ServiceResource\n readonly users: UserResource\n readonly config: AmigoSdkConfig\n\n constructor(config: AmigoSdkConfig) {\n this.config = validateConfig(config)\n\n const api = createAmigoFetch(this.config)\n this.organizations = new OrganizationResource(api, this.config.orgId)\n this.conversations = new ConversationResource(api, this.config.orgId)\n this.services = new ServiceResource(api, this.config.orgId)\n this.users = new UserResource(api, this.config.orgId)\n }\n}\n\nfunction validateConfig(config: AmigoSdkConfig) {\n if (!config.apiKey) {\n throw new ConfigurationError('API key is required', 'apiKey')\n }\n if (!config.apiKeyId) {\n throw new ConfigurationError('API key ID is required', 'apiKeyId')\n }\n if (!config.userId) {\n throw new ConfigurationError('User ID is required', 'userId')\n }\n if (!config.orgId) {\n throw new ConfigurationError('Organization ID is required', 'orgId')\n }\n if (!config.baseUrl) {\n config.baseUrl = defaultBaseUrl\n }\n return config\n}\n\n// Export all errors as a namespace to avoid polluting the main import space\nexport * as errors from './core/errors'\n\n// Re-export useful types for consumers\nexport type { components, operations, paths } from './generated/api-types'\n"],
5
+ "mappings": ";;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,eAAsB,YACpB,iBAC6B;AAC7B,QAAM,SAAS,MAAM;AACrB,QAAM,OAAQ,OAAyC;AAEvD,MAAI,SAAS,UAAa,SAAS,MAAM;AAGvC,UAAM,IAAI,WAAW,+DAA+D,UAAU;AAAA,EAChG;AAEA,SAAO;AACT;AAMA,gBAAuB,kBAA+B,UAAuC;AAC3F,QAAM,OAAO,SAAS;AACtB,MAAI,CAAC,KAAM;AAEX,QAAM,SAAS,KAAK,UAAU;AAC9B,QAAM,UAAU,IAAI,YAAY;A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",
6
6
  "names": ["isNetworkError"]
7
7
  }
@@ -2267,7 +2267,7 @@ export interface components {
2267
2267
  /** Boundary Constraints */
2268
2268
  boundary_constraints: components["schemas"]["amigo_lib__pydantic__base_model__StrippedNonemptyString__1"][];
2269
2269
  /** Exit Conditions */
2270
- exit_conditions: components["schemas"]["organization__create_service_hierarchical_state_machine_version__Request__DecisionState__ExitCondition"][];
2270
+ exit_conditions: components["schemas"]["organization__create_service_hierarchical_state_machine_version__Request__ActionState__ExitCondition"][];
2271
2271
  /** Action Tool Call Specs */
2272
2272
  action_tool_call_specs: components["schemas"]["organization__create_service_hierarchical_state_machine_version__Request__ToolCallSpec"][];
2273
2273
  /** Exit Condition Tool Call Specs */
@@ -2688,7 +2688,7 @@ export interface components {
2688
2688
  type: "decision";
2689
2689
  name: components["schemas"]["StateOrRefName"];
2690
2690
  /** Exit Conditions */
2691
- exit_conditions: components["schemas"]["organization__create_service_hierarchical_state_machine_version__Request__DecisionState__ExitCondition"][];
2691
+ exit_conditions: components["schemas"]["organization__create_service_hierarchical_state_machine_version__Request__ActionState__ExitCondition"][];
2692
2692
  /** Decision Guidelines */
2693
2693
  decision_guidelines: components["schemas"]["amigo_lib__pydantic__base_model__StrippedNonemptyString__1"][];
2694
2694
  objective: components["schemas"]["amigo_lib__pydantic__base_model__StrippedNonemptyString__1"];
@@ -3432,7 +3432,7 @@ export interface components {
3432
3432
  * Tags
3433
3433
  * @description The tags of the metric.
3434
3434
  */
3435
- tags: components["schemas"]["amigo_lib__mongo__collections__metric__Metric__Tag"][];
3435
+ tags: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__Tag"][];
3436
3436
  /** @description The user who created the metric. */
3437
3437
  creator: components["schemas"]["amigo_lib__mongo__collections__metric__Metric__UserInfo"];
3438
3438
  /** @description The user who last updated the metric. */
@@ -3537,7 +3537,7 @@ export interface components {
3537
3537
  * Tags
3538
3538
  * @description The tags of the metric.
3539
3539
  */
3540
- tags: components["schemas"]["amigo_lib__mongo__collections__metric__Metric__Tag"][];
3540
+ tags: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__Tag"][];
3541
3541
  /** @description The user who created the metric. */
3542
3542
  creator: components["schemas"]["amigo_lib__mongo__collections__metric__Metric__UserInfo"];
3543
3543
  /** @description The user who last updated the metric. */
@@ -4396,7 +4396,7 @@ export interface components {
4396
4396
  * Tags
4397
4397
  * @description The tags of the service.
4398
4398
  */
4399
- tags: components["schemas"]["amigo_lib__mongo__collections__metric__Metric__Tag"][];
4399
+ tags: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__Tag"][];
4400
4400
  };
4401
4401
  /** SimulationConversationInvocationSource */
4402
4402
  SimulationConversationInvocationSource: {
@@ -4606,7 +4606,7 @@ export interface components {
4606
4606
  * Tags
4607
4607
  * @description The tags of the simulation persona.
4608
4608
  */
4609
- tags: components["schemas"]["amigo_lib__mongo__collections__metric__Metric__Tag"][];
4609
+ tags: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__Tag"][];
4610
4610
  creator: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__UserInfo"];
4611
4611
  updated_by: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__UserInfo"];
4612
4612
  };
@@ -4678,7 +4678,7 @@ export interface components {
4678
4678
  * Tags
4679
4679
  * @description The tags of the simulation persona.
4680
4680
  */
4681
- tags: components["schemas"]["amigo_lib__mongo__collections__metric__Metric__Tag"][];
4681
+ tags: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__Tag"][];
4682
4682
  creator: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__UserInfo"];
4683
4683
  updated_by: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__UserInfo"];
4684
4684
  };
@@ -4733,7 +4733,7 @@ export interface components {
4733
4733
  * Tags
4734
4734
  * @description The tags of the simulation unit test set.
4735
4735
  */
4736
- tags: components["schemas"]["amigo_lib__mongo__collections__metric__Metric__Tag"][];
4736
+ tags: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__Tag"][];
4737
4737
  creator: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test_set__SimulationUnitTestSet__UserInfo"];
4738
4738
  updated_by: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test_set__SimulationUnitTestSet__UserInfo"];
4739
4739
  };
@@ -4785,7 +4785,7 @@ export interface components {
4785
4785
  * Tags
4786
4786
  * @description The tags of the simulation unit test set.
4787
4787
  */
4788
- tags: components["schemas"]["amigo_lib__mongo__collections__metric__Metric__Tag"][];
4788
+ tags: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__Tag"][];
4789
4789
  creator: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test_set__SimulationUnitTestSet__UserInfo"];
4790
4790
  updated_by: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test_set__SimulationUnitTestSet__UserInfo"];
4791
4791
  };
@@ -5247,7 +5247,7 @@ export interface components {
5247
5247
  * Tags
5248
5248
  * @description The tags of the simulation persona.
5249
5249
  */
5250
- tags: components["schemas"]["amigo_lib__mongo__collections__metric__Metric__Tag"][];
5250
+ tags: components["schemas"]["amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__Tag"][];
5251
5251
  };
5252
5252
  /** ToolVersionInstance */
5253
5253
  ToolVersionInstance: {
@@ -5781,13 +5781,6 @@ export interface components {
5781
5781
  */
5782
5782
  tool_name: string;
5783
5783
  };
5784
- /** Tag */
5785
- amigo_lib__mongo__collections__metric__Metric__Tag: {
5786
- /** Key */
5787
- key: string;
5788
- /** Value */
5789
- value: string | null;
5790
- };
5791
5784
  /** UserInfo */
5792
5785
  amigo_lib__mongo__collections__metric__Metric__UserInfo: {
5793
5786
  /** Org Id */
@@ -5911,6 +5904,13 @@ export interface components {
5911
5904
  metric_id: string;
5912
5905
  criterion: components["schemas"]["SuccessCriterionDescription-Output"];
5913
5906
  };
5907
+ /** Tag */
5908
+ amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__Tag: {
5909
+ /** Key */
5910
+ key: string;
5911
+ /** Value */
5912
+ value: string | null;
5913
+ };
5914
5914
  /** UserInfo */
5915
5915
  amigo_lib__mongo__collections__simulation_unit_test__SimulationUnitTest__UserInfo: {
5916
5916
  /** Org Id */
@@ -6278,7 +6278,7 @@ export interface components {
6278
6278
  * Actions
6279
6279
  * @description The action to perform when the dynamic behavior set version is activated.
6280
6280
  */
6281
- actions: (components["schemas"]["dynamic_behavior_set__create_dynamic_behavior_set__Request__InitialVersion__InjectInstructionAction"] | components["schemas"]["dynamic_behavior_set__create_dynamic_behavior_set__Request__InitialVersion__ChangeToolCandidatesAction"])[];
6281
+ actions: (components["schemas"]["dynamic_behavior_set__create_dynamic_behavior_set_version__Request__InjectInstructionAction"] | components["schemas"]["dynamic_behavior_set__create_dynamic_behavior_set__Request__InitialVersion__ChangeToolCandidatesAction"])[];
6282
6282
  };
6283
6283
  /** ChangeToolCandidatesAction */
6284
6284
  dynamic_behavior_set__create_dynamic_behavior_set__Request__InitialVersion__ChangeToolCandidatesAction: {
@@ -6329,20 +6329,6 @@ export interface components {
6329
6329
  * the context of the dynamic behavior. */
6330
6330
  tool_name: components["schemas"]["amigo_lib__pydantic__base_model__StrippedNonemptyString__1"];
6331
6331
  };
6332
- /** InjectInstructionAction */
6333
- dynamic_behavior_set__create_dynamic_behavior_set__Request__InitialVersion__InjectInstructionAction: {
6334
- /**
6335
- * @description discriminator enum property added by openapi-typescript
6336
- * @enum {string}
6337
- */
6338
- type: "dynamic_behavior_set__create_dynamic_behavior_set__Request__InitialVersion__InjectInstructionAction";
6339
- instruction: components["schemas"]["amigo_lib__pydantic__base_model__StrippedNonemptyString__1"];
6340
- /**
6341
- * Overrides Instructions
6342
- * @description During injection, whether the original instruction of the state is overriden with this instruction.
6343
- */
6344
- overrides_instructions: boolean;
6345
- };
6346
6332
  /** Response */
6347
6333
  dynamic_behavior_set__create_dynamic_behavior_set__Response: {
6348
6334
  /**
@@ -6362,7 +6348,7 @@ export interface components {
6362
6348
  * Actions
6363
6349
  * @description The action to perform when the dynamic behavior set version is activated.
6364
6350
  */
6365
- actions: (components["schemas"]["dynamic_behavior_set__create_dynamic_behavior_set__Request__InitialVersion__InjectInstructionAction"] | components["schemas"]["dynamic_behavior_set__create_dynamic_behavior_set_version__Request__ChangeToolCandidatesAction"])[];
6351
+ actions: (components["schemas"]["dynamic_behavior_set__create_dynamic_behavior_set_version__Request__InjectInstructionAction"] | components["schemas"]["dynamic_behavior_set__create_dynamic_behavior_set_version__Request__ChangeToolCandidatesAction"])[];
6366
6352
  };
6367
6353
  /** ChangeToolCandidatesAction */
6368
6354
  dynamic_behavior_set__create_dynamic_behavior_set_version__Request__ChangeToolCandidatesAction: {
@@ -6413,6 +6399,20 @@ export interface components {
6413
6399
  * the context of the dynamic behavior. */
6414
6400
  tool_name: components["schemas"]["amigo_lib__pydantic__base_model__StrippedNonemptyString__1"];
6415
6401
  };
6402
+ /** InjectInstructionAction */
6403
+ dynamic_behavior_set__create_dynamic_behavior_set_version__Request__InjectInstructionAction: {
6404
+ /**
6405
+ * @description discriminator enum property added by openapi-typescript
6406
+ * @enum {string}
6407
+ */
6408
+ type: "dynamic_behavior_set__create_dynamic_behavior_set_version__Request__InjectInstructionAction";
6409
+ instruction: components["schemas"]["amigo_lib__pydantic__base_model__StrippedNonemptyString__1"];
6410
+ /**
6411
+ * Overrides Instructions
6412
+ * @description During injection, whether the original instruction of the state is overriden with this instruction.
6413
+ */
6414
+ overrides_instructions: boolean;
6415
+ };
6416
6416
  /** Response */
6417
6417
  dynamic_behavior_set__create_dynamic_behavior_set_version__Response: {
6418
6418
  /**
@@ -6997,7 +6997,7 @@ export interface components {
6997
6997
  global_boundary_constraints: components["schemas"]["amigo_lib__pydantic__base_model__StrippedNonemptyString__1"][];
6998
6998
  };
6999
6999
  /** ExitCondition */
7000
- organization__create_service_hierarchical_state_machine_version__Request__DecisionState__ExitCondition: {
7000
+ organization__create_service_hierarchical_state_machine_version__Request__ActionState__ExitCondition: {
7001
7001
  description: components["schemas"]["amigo_lib__pydantic__base_model__StrippedNonemptyString__1"];
7002
7002
  /** Next State */
7003
7003
  next_state: components["schemas"]["StateOrRefName"] | [
@@ -7454,7 +7454,7 @@ export interface components {
7454
7454
  is_active: boolean;
7455
7455
  /** @description The `release` version set to use for this service. If not specified, the `release` version set will be the same as the `edge` version set, which uses the
7456
7456
  * latest agent and state machine versions with no model preference. */
7457
- release_version_set?: components["schemas"]["service__create_service__Request__VersionSet"] | null;
7457
+ release_version_set?: components["schemas"]["service__upsert_service_version_set__Request__VersionSet"] | null;
7458
7458
  /**
7459
7459
  * Keyterms
7460
7460
  * @description A list of keyterms that are easy to get wrong during audio transcriptions that tend to occur commonly in audio sessions using this service.
@@ -7469,21 +7469,16 @@ export interface components {
7469
7469
  [key: string]: components["schemas"]["StrippedNonemptyString___w__s_____"] | null;
7470
7470
  };
7471
7471
  };
7472
- /** VersionSet */
7473
- service__create_service__Request__VersionSet: {
7474
- /**
7475
- * Agent Version Number
7476
- * @description The version number of the agent to be used. If None, the latest agent version will be used.
7477
- */
7478
- agent_version_number: number | null;
7472
+ /** LLMConfig */
7473
+ service__create_service__Request__VersionSet__LLMConfig: {
7474
+ llm_name: components["schemas"]["LLMType"];
7479
7475
  /**
7480
- * Service Hierarchical State Machine Version Number
7481
- * @description The version number of the state machine to be used. If None, the latest state machine version will be used.
7476
+ * Params
7477
+ * @description LLM-specific parameters to use.
7478
+ * @default {}
7482
7479
  */
7483
- service_hierarchical_state_machine_version_number: number | null;
7484
- /** Llm Model Preferences */
7485
- llm_model_preferences: {
7486
- [key: string]: components["schemas"]["service__upsert_service_version_set__Request__VersionSet__LLMConfig"];
7480
+ params?: {
7481
+ [key: string]: unknown;
7487
7482
  };
7488
7483
  };
7489
7484
  /** Response */
@@ -7566,18 +7561,23 @@ export interface components {
7566
7561
  /** Request */
7567
7562
  service__upsert_service_version_set__Request: {
7568
7563
  /** @description The version set to upsert. */
7569
- version_set: components["schemas"]["service__create_service__Request__VersionSet"];
7564
+ version_set: components["schemas"]["service__upsert_service_version_set__Request__VersionSet"];
7570
7565
  };
7571
- /** LLMConfig */
7572
- service__upsert_service_version_set__Request__VersionSet__LLMConfig: {
7573
- llm_name: components["schemas"]["LLMType"];
7566
+ /** VersionSet */
7567
+ service__upsert_service_version_set__Request__VersionSet: {
7574
7568
  /**
7575
- * Params
7576
- * @description LLM-specific parameters to use.
7577
- * @default {}
7569
+ * Agent Version Number
7570
+ * @description The version number of the agent to be used. If None, the latest agent version will be used.
7578
7571
  */
7579
- params?: {
7580
- [key: string]: unknown;
7572
+ agent_version_number: number | null;
7573
+ /**
7574
+ * Service Hierarchical State Machine Version Number
7575
+ * @description The version number of the state machine to be used. If None, the latest state machine version will be used.
7576
+ */
7577
+ service_hierarchical_state_machine_version_number: number | null;
7578
+ /** Llm Model Preferences */
7579
+ llm_model_preferences: {
7580
+ [key: string]: components["schemas"]["service__create_service__Request__VersionSet__LLMConfig"];
7581
7581
  };
7582
7582
  };
7583
7583
  /** Request */
@@ -8335,7 +8335,7 @@ export interface components {
8335
8335
  * Tool Invocations
8336
8336
  * @description The list of tool invocations.
8337
8337
  */
8338
- tool_invocations: components["schemas"]["tool__get_tool_invocations__Response__ToolInvocationInstance"][];
8338
+ tool_invocations: components["schemas"]["tool__search_tool_invocations__Response__ToolInvocationInstance"][];
8339
8339
  /**
8340
8340
  * Has More
8341
8341
  * @description Whether there are more tool invocations to retrieve.
@@ -8347,47 +8347,6 @@ export interface components {
8347
8347
  */
8348
8348
  continuation_token: unknown | null;
8349
8349
  };
8350
- /** ToolInvocationInstance */
8351
- tool__get_tool_invocations__Response__ToolInvocationInstance: {
8352
- /**
8353
- * Id
8354
- * @description The ID of the tool invocation.
8355
- */
8356
- id: string;
8357
- /**
8358
- * Org Id
8359
- * @description The ID of the organization.
8360
- */
8361
- org_id: string;
8362
- /**
8363
- * Created At
8364
- * Format: date-time
8365
- */
8366
- created_at?: string;
8367
- /**
8368
- * Updated At
8369
- * Format: date-time
8370
- */
8371
- updated_at?: string;
8372
- /** @description The status of the tool invocation. */
8373
- invocation_status: components["schemas"]["InvocationStatus"];
8374
- /** @description The source of the tool invocation. */
8375
- invocation_source: components["schemas"]["InvocationSource"];
8376
- /** Logs */
8377
- logs: string[];
8378
- /**
8379
- * Duration Ms
8380
- * @description The duration of the tool invocation in milliseconds.
8381
- */
8382
- duration_ms: number;
8383
- /**
8384
- * Tool Id
8385
- * @description The ID of the tool that was invoked.
8386
- */
8387
- tool_id: string;
8388
- /** @description The version of the tool that was invoked. */
8389
- tool_version: components["schemas"]["amigo_lib__mongo__collections__tool_version__ToolVersion__Version"];
8390
- };
8391
8350
  /** Response */
8392
8351
  tool__get_tool_versions__Response: {
8393
8352
  /**
@@ -8544,7 +8503,48 @@ export interface components {
8544
8503
  * Tool Invocations
8545
8504
  * @description The list of tool invocations.
8546
8505
  */
8547
- tool_invocations: components["schemas"]["tool__get_tool_invocations__Response__ToolInvocationInstance"][];
8506
+ tool_invocations: components["schemas"]["tool__search_tool_invocations__Response__ToolInvocationInstance"][];
8507
+ };
8508
+ /** ToolInvocationInstance */
8509
+ tool__search_tool_invocations__Response__ToolInvocationInstance: {
8510
+ /**
8511
+ * Id
8512
+ * @description The ID of the tool invocation.
8513
+ */
8514
+ id: string;
8515
+ /**
8516
+ * Org Id
8517
+ * @description The ID of the organization.
8518
+ */
8519
+ org_id: string;
8520
+ /**
8521
+ * Created At
8522
+ * Format: date-time
8523
+ */
8524
+ created_at?: string;
8525
+ /**
8526
+ * Updated At
8527
+ * Format: date-time
8528
+ */
8529
+ updated_at?: string;
8530
+ /** @description The status of the tool invocation. */
8531
+ invocation_status: components["schemas"]["InvocationStatus"];
8532
+ /** @description The source of the tool invocation. */
8533
+ invocation_source: components["schemas"]["InvocationSource"];
8534
+ /** Logs */
8535
+ logs: string[];
8536
+ /**
8537
+ * Duration Ms
8538
+ * @description The duration of the tool invocation in milliseconds.
8539
+ */
8540
+ duration_ms: number;
8541
+ /**
8542
+ * Tool Id
8543
+ * @description The ID of the tool that was invoked.
8544
+ */
8545
+ tool_id: string;
8546
+ /** @description The version of the tool that was invoked. */
8547
+ tool_version: components["schemas"]["amigo_lib__mongo__collections__tool_version__ToolVersion__Version"];
8548
8548
  };
8549
8549
  /** Request */
8550
8550
  tool__test_tool__Request: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amigo-ai/sdk",
3
- "version": "0.64.0",
3
+ "version": "0.65.0",
4
4
  "description": "Amigo TypeScript SDK",
5
5
  "publishConfig": {
6
6
  "access": "public"