@amigo-ai/sdk 0.100.0 → 0.100.1
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/README.md +26 -0
- package/dist/index.cjs +14 -2
- package/dist/index.cjs.map +2 -2
- package/dist/index.mjs +14 -2
- package/dist/index.mjs.map +2 -2
- package/dist/types/core/openapi-client.d.ts +1 -0
- package/dist/types/core/retry.d.ts +2 -0
- package/dist/types/generated/api-types.d.ts +1634 -807
- package/dist/types/index.d.ts +5 -0
- package/dist/types/resources/conversation.d.ts +10 -0
- package/dist/types/resources/organization.d.ts +2 -1
- package/dist/types/resources/services.d.ts +1 -0
- package/dist/types/resources/user.d.ts +6 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -139,6 +139,32 @@ try {
|
|
|
139
139
|
}
|
|
140
140
|
```
|
|
141
141
|
|
|
142
|
+
## Troubleshooting
|
|
143
|
+
|
|
144
|
+
### Authentication errors
|
|
145
|
+
|
|
146
|
+
- **`AuthenticationError: Authentication failed`**: Verify your `apiKey` and `apiKeyId` are correct and haven't been revoked. Regenerate them from the Amigo dashboard if needed.
|
|
147
|
+
- **Token refresh failures**: The SDK refreshes tokens automatically 5 minutes before expiry. If this persists, check that your system clock is accurate.
|
|
148
|
+
|
|
149
|
+
### Configuration issues
|
|
150
|
+
|
|
151
|
+
- **`ConfigurationError`**: Ensure all required fields (`apiKey`, `apiKeyId`, `userId`, `orgId`) are provided when constructing `AmigoClient`.
|
|
152
|
+
|
|
153
|
+
### Connection issues
|
|
154
|
+
|
|
155
|
+
- **`NetworkError` or timeouts**: Check your network connectivity and that `https://api.amigo.ai` is reachable. If behind a corporate proxy, configure your environment's proxy settings.
|
|
156
|
+
- **`RateLimitError`**: The SDK retries automatically on 429 responses with `Retry-After` headers. If you consistently hit rate limits, reduce request frequency or contact support.
|
|
157
|
+
|
|
158
|
+
### TypeScript / import issues
|
|
159
|
+
|
|
160
|
+
- **`Cannot find module '@amigo-ai/sdk'`**: Ensure the package is installed: `npm install @amigo-ai/sdk`.
|
|
161
|
+
- **Type errors with generated types**: Update to the latest SDK version (`npm install @amigo-ai/sdk@latest`) — types are regenerated from the OpenAPI spec on each release.
|
|
162
|
+
- **ESM/CJS import issues**: The SDK supports both. Use `import { AmigoClient } from '@amigo-ai/sdk'` for ESM or `const { AmigoClient } = require('@amigo-ai/sdk')` for CJS. Ensure your `tsconfig.json` has compatible `moduleResolution` settings.
|
|
163
|
+
|
|
164
|
+
### Streaming issues
|
|
165
|
+
|
|
166
|
+
- **NDJSON stream not yielding events**: Ensure you're using `for await` to consume the async generator returned by `createConversation` and `interactWithConversation`.
|
|
167
|
+
|
|
142
168
|
## Documentation
|
|
143
169
|
|
|
144
170
|
- **Developer Guide**: [https://docs.amigo.ai/developer-guide](https://docs.amigo.ai/developer-guide)
|
package/dist/index.cjs
CHANGED
|
@@ -524,6 +524,7 @@ var ConversationResource = class {
|
|
|
524
524
|
this.c = c;
|
|
525
525
|
this.orgId = orgId;
|
|
526
526
|
}
|
|
527
|
+
/** Create a new conversation and return an async stream of NDJSON events. */
|
|
527
528
|
async createConversation(body, queryParams, headers, options) {
|
|
528
529
|
const resp = await this.c.POST("/v1/{organization}/conversation/", {
|
|
529
530
|
params: { path: { organization: this.orgId }, query: queryParams },
|
|
@@ -540,6 +541,7 @@ var ConversationResource = class {
|
|
|
540
541
|
resp.response
|
|
541
542
|
);
|
|
542
543
|
}
|
|
544
|
+
/** Send a text or voice interaction and return an async stream of NDJSON events. */
|
|
543
545
|
async interactWithConversation(conversationId, input, queryParams, headers, options) {
|
|
544
546
|
let bodyToSend;
|
|
545
547
|
const mergedHeaders = {
|
|
@@ -593,6 +595,7 @@ var ConversationResource = class {
|
|
|
593
595
|
});
|
|
594
596
|
return parseNdjsonStream(resp.response);
|
|
595
597
|
}
|
|
598
|
+
/** List conversations, optionally filtered by query parameters. */
|
|
596
599
|
async getConversations(queryParams, headers) {
|
|
597
600
|
return extractData(
|
|
598
601
|
this.c.GET("/v1/{organization}/conversation/", {
|
|
@@ -601,6 +604,7 @@ var ConversationResource = class {
|
|
|
601
604
|
})
|
|
602
605
|
);
|
|
603
606
|
}
|
|
607
|
+
/** Get messages for a conversation. */
|
|
604
608
|
async getConversationMessages(conversationId, queryParams, headers) {
|
|
605
609
|
return extractData(
|
|
606
610
|
this.c.GET("/v1/{organization}/conversation/{conversation_id}/messages/", {
|
|
@@ -612,6 +616,7 @@ var ConversationResource = class {
|
|
|
612
616
|
})
|
|
613
617
|
);
|
|
614
618
|
}
|
|
619
|
+
/** Finish (close) a conversation. */
|
|
615
620
|
async finishConversation(conversationId, headers) {
|
|
616
621
|
await this.c.POST("/v1/{organization}/conversation/{conversation_id}/finish/", {
|
|
617
622
|
params: { path: { organization: this.orgId, conversation_id: conversationId } },
|
|
@@ -621,6 +626,7 @@ var ConversationResource = class {
|
|
|
621
626
|
});
|
|
622
627
|
return;
|
|
623
628
|
}
|
|
629
|
+
/** Get recommended responses for an interaction. */
|
|
624
630
|
async recommendResponsesForInteraction(conversationId, interactionId, body, headers) {
|
|
625
631
|
return extractData(
|
|
626
632
|
this.c.POST(
|
|
@@ -639,6 +645,7 @@ var ConversationResource = class {
|
|
|
639
645
|
)
|
|
640
646
|
);
|
|
641
647
|
}
|
|
648
|
+
/** Get insights for an interaction. */
|
|
642
649
|
async getInteractionInsights(conversationId, interactionId, headers) {
|
|
643
650
|
return extractData(
|
|
644
651
|
this.c.GET(
|
|
@@ -656,8 +663,7 @@ var ConversationResource = class {
|
|
|
656
663
|
)
|
|
657
664
|
);
|
|
658
665
|
}
|
|
659
|
-
|
|
660
|
-
// TODO -- fix response typing.
|
|
666
|
+
/** Get the audio/media source URL for a message. */
|
|
661
667
|
async getMessageSource(conversationId, messageId, headers) {
|
|
662
668
|
return extractData(
|
|
663
669
|
this.c.GET("/v1/{organization}/conversation/{conversation_id}/messages/{message_id}/source", {
|
|
@@ -672,6 +678,7 @@ var ConversationResource = class {
|
|
|
672
678
|
})
|
|
673
679
|
);
|
|
674
680
|
}
|
|
681
|
+
/** Generate conversation starter suggestions. */
|
|
675
682
|
async generateConversationStarters(body, headers) {
|
|
676
683
|
return extractData(
|
|
677
684
|
this.c.POST("/v1/{organization}/conversation/conversation_starter", {
|
|
@@ -710,6 +717,7 @@ var UserResource = class {
|
|
|
710
717
|
this.c = c;
|
|
711
718
|
this.orgId = orgId;
|
|
712
719
|
}
|
|
720
|
+
/** List users in the organization. */
|
|
713
721
|
async getUsers(queryParams, headers) {
|
|
714
722
|
return extractData(
|
|
715
723
|
this.c.GET("/v1/{organization}/user/", {
|
|
@@ -718,6 +726,7 @@ var UserResource = class {
|
|
|
718
726
|
})
|
|
719
727
|
);
|
|
720
728
|
}
|
|
729
|
+
/** Create (invite) a new user to the organization. */
|
|
721
730
|
async createUser(body, headers) {
|
|
722
731
|
return extractData(
|
|
723
732
|
this.c.POST("/v1/{organization}/user/", {
|
|
@@ -727,6 +736,7 @@ var UserResource = class {
|
|
|
727
736
|
})
|
|
728
737
|
);
|
|
729
738
|
}
|
|
739
|
+
/** Delete a user by ID. */
|
|
730
740
|
async deleteUser(userId, headers) {
|
|
731
741
|
await this.c.DELETE("/v1/{organization}/user/{requested_user_id}", {
|
|
732
742
|
params: { path: { organization: this.orgId, requested_user_id: userId } },
|
|
@@ -734,6 +744,7 @@ var UserResource = class {
|
|
|
734
744
|
});
|
|
735
745
|
return;
|
|
736
746
|
}
|
|
747
|
+
/** Update user information. */
|
|
737
748
|
async updateUser(userId, body, headers) {
|
|
738
749
|
await this.c.POST("/v1/{organization}/user/{requested_user_id}", {
|
|
739
750
|
params: { path: { organization: this.orgId, requested_user_id: userId } },
|
|
@@ -755,6 +766,7 @@ var UserResource = class {
|
|
|
755
766
|
// src/index.ts
|
|
756
767
|
var defaultBaseUrl = "https://api.amigo.ai";
|
|
757
768
|
var AmigoClient = class {
|
|
769
|
+
/** Create a new Amigo client with the given configuration. */
|
|
758
770
|
constructor(config) {
|
|
759
771
|
__publicField(this, "organizations");
|
|
760
772
|
__publicField(this, "conversations");
|
package/dist/index.cjs.map
CHANGED
|
@@ -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 type { Client } from 'openapi-fetch'\nimport openapiFetchImport from 'openapi-fetch'\nimport { createErrorMiddleware } from './errors'\n\n// Handle ESM/CJS interop: esbuild's __toESM wrapper can cause the default\n// import to be the module object ({ default: fn }) instead of the function directly.\n// This normalizes access to work in both environments.\nconst createClient: typeof openapiFetchImport =\n typeof openapiFetchImport === 'function'\n ? openapiFetchImport\n : (openapiFetchImport as unknown as { default: typeof openapiFetchImport }).default\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,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;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\n/**\n * Main client for the Amigo API.\n * Provides access to all API resources (organizations, conversations, services, users).\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 /** Create a new Amigo client with the given configuration. */\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 type { Client } from 'openapi-fetch'\nimport openapiFetchImport from 'openapi-fetch'\nimport { createErrorMiddleware } from './errors'\n\n// Handle ESM/CJS interop: esbuild's __toESM wrapper can cause the default\n// import to be the module object ({ default: fn }) instead of the function directly.\n// This normalizes access to work in both environments.\nconst createClient: typeof openapiFetchImport =\n typeof openapiFetchImport === 'function'\n ? openapiFetchImport\n : (openapiFetchImport as unknown as { default: typeof openapiFetchImport }).default\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\n/** Create an OpenAPI-typed fetch client with auth, error handling, and retry middleware. */\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\n/** Merge user-provided retry options with sensible defaults. */\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\n/** Wrap a fetch function with retry logic (exponential backoff, Retry-After support). */\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\n/** Resource for retrieving organization details. */\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\n/** Resource for managing conversations and interactions. */\nexport class ConversationResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n /** Create a new conversation and return an async stream of NDJSON events. */\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 /** Send a text or voice interaction and return an async stream of NDJSON events. */\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 /** List conversations, optionally filtered by query parameters. */\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 /** Get messages for a conversation. */\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 /** Finish (close) a conversation. */\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 /** Get recommended responses for an interaction. */\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 /** Get insights for an interaction. */\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 /** Get the audio/media source URL for a message. */\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 /** Generate conversation starter suggestions. */\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\n/** Resource for retrieving available services. */\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\n/** Resource for managing users in the organization. */\nexport class UserResource {\n constructor(\n private c: AmigoFetch,\n private orgId: string\n ) {}\n\n /** List users in the organization. */\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 /** Create (invite) a new user to the organization. */\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 /** Delete a user by ID. */\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 /** Update user information. */\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,QAAM,OAAO,SAAS;AACtB,MAAI,CAAC,KAAM;AAEX,QAAM,SAAS,KAAK,UAAU;AAC9B,QAAM,UAAU,IAAI,YAAY;AAChC,MAAI,eAAe;AAEnB,MAAI;AACF,WAAO,MAAM;AACX,YAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAC1C,UAAI,KAAM;AACV,sBAAgB,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC;AAEtD,UAAI;AAEJ,cAAQ,eAAe,aAAa,QAAQ,IAAI,OAAO,IAAI;AACzD,cAAM,OAAO,aAAa,MAAM,GAAG,YAAY,EAAE,KAAK;AACtD,uBAAe,aAAa,MAAM,eAAe,CAAC;AAClD,YAAI,CAAC,KAAM;AACX,YAAI;AACF,gBAAM,KAAK,MAAM,IAAI;AAAA,QACvB,SAAS,KAAK;AACZ,gBAAM,IAAI,WAAW,+BAA+B,QAAQ,GAAY;AAAA,QAC1E;AAAA,M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AAM,iBAAiB;AAMhB,IAAM,cAAN,MAAkB;AAAA;AAAA,EAQvB,YAAY,QAAwB;AAPpC,wBAAS;AACT,wBAAS;AACT,wBAAS;AACT,wBAAS;AACT,wBAAS;AAIP,SAAK,SAAS,eAAe,MAAM;AAEnC,UAAM,MAAM,iBAAiB,KAAK,MAAM;AACxC,SAAK,gBAAgB,IAAI,qBAAqB,KAAK,KAAK,OAAO,KAAK;AACpE,SAAK,gBAAgB,IAAI,qBAAqB,KAAK,KAAK,OAAO,KAAK;AACpE,SAAK,WAAW,IAAI,gBAAgB,KAAK,KAAK,OAAO,KAAK;AAC1D,SAAK,QAAQ,IAAI,aAAa,KAAK,KAAK,OAAO,KAAK;AAAA,EACtD;AACF;AAEA,SAAS,eAAe,QAAwB;AAC9C,MAAI,CAAC,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;",
|
|
6
6
|
"names": ["isNetworkError", "openapiFetchImport"]
|
|
7
7
|
}
|
package/dist/index.mjs
CHANGED
|
@@ -493,6 +493,7 @@ var ConversationResource = class {
|
|
|
493
493
|
this.c = c;
|
|
494
494
|
this.orgId = orgId;
|
|
495
495
|
}
|
|
496
|
+
/** Create a new conversation and return an async stream of NDJSON events. */
|
|
496
497
|
async createConversation(body, queryParams, headers, options) {
|
|
497
498
|
const resp = await this.c.POST("/v1/{organization}/conversation/", {
|
|
498
499
|
params: { path: { organization: this.orgId }, query: queryParams },
|
|
@@ -509,6 +510,7 @@ var ConversationResource = class {
|
|
|
509
510
|
resp.response
|
|
510
511
|
);
|
|
511
512
|
}
|
|
513
|
+
/** Send a text or voice interaction and return an async stream of NDJSON events. */
|
|
512
514
|
async interactWithConversation(conversationId, input, queryParams, headers, options) {
|
|
513
515
|
let bodyToSend;
|
|
514
516
|
const mergedHeaders = {
|
|
@@ -562,6 +564,7 @@ var ConversationResource = class {
|
|
|
562
564
|
});
|
|
563
565
|
return parseNdjsonStream(resp.response);
|
|
564
566
|
}
|
|
567
|
+
/** List conversations, optionally filtered by query parameters. */
|
|
565
568
|
async getConversations(queryParams, headers) {
|
|
566
569
|
return extractData(
|
|
567
570
|
this.c.GET("/v1/{organization}/conversation/", {
|
|
@@ -570,6 +573,7 @@ var ConversationResource = class {
|
|
|
570
573
|
})
|
|
571
574
|
);
|
|
572
575
|
}
|
|
576
|
+
/** Get messages for a conversation. */
|
|
573
577
|
async getConversationMessages(conversationId, queryParams, headers) {
|
|
574
578
|
return extractData(
|
|
575
579
|
this.c.GET("/v1/{organization}/conversation/{conversation_id}/messages/", {
|
|
@@ -581,6 +585,7 @@ var ConversationResource = class {
|
|
|
581
585
|
})
|
|
582
586
|
);
|
|
583
587
|
}
|
|
588
|
+
/** Finish (close) a conversation. */
|
|
584
589
|
async finishConversation(conversationId, headers) {
|
|
585
590
|
await this.c.POST("/v1/{organization}/conversation/{conversation_id}/finish/", {
|
|
586
591
|
params: { path: { organization: this.orgId, conversation_id: conversationId } },
|
|
@@ -590,6 +595,7 @@ var ConversationResource = class {
|
|
|
590
595
|
});
|
|
591
596
|
return;
|
|
592
597
|
}
|
|
598
|
+
/** Get recommended responses for an interaction. */
|
|
593
599
|
async recommendResponsesForInteraction(conversationId, interactionId, body, headers) {
|
|
594
600
|
return extractData(
|
|
595
601
|
this.c.POST(
|
|
@@ -608,6 +614,7 @@ var ConversationResource = class {
|
|
|
608
614
|
)
|
|
609
615
|
);
|
|
610
616
|
}
|
|
617
|
+
/** Get insights for an interaction. */
|
|
611
618
|
async getInteractionInsights(conversationId, interactionId, headers) {
|
|
612
619
|
return extractData(
|
|
613
620
|
this.c.GET(
|
|
@@ -625,8 +632,7 @@ var ConversationResource = class {
|
|
|
625
632
|
)
|
|
626
633
|
);
|
|
627
634
|
}
|
|
628
|
-
|
|
629
|
-
// TODO -- fix response typing.
|
|
635
|
+
/** Get the audio/media source URL for a message. */
|
|
630
636
|
async getMessageSource(conversationId, messageId, headers) {
|
|
631
637
|
return extractData(
|
|
632
638
|
this.c.GET("/v1/{organization}/conversation/{conversation_id}/messages/{message_id}/source", {
|
|
@@ -641,6 +647,7 @@ var ConversationResource = class {
|
|
|
641
647
|
})
|
|
642
648
|
);
|
|
643
649
|
}
|
|
650
|
+
/** Generate conversation starter suggestions. */
|
|
644
651
|
async generateConversationStarters(body, headers) {
|
|
645
652
|
return extractData(
|
|
646
653
|
this.c.POST("/v1/{organization}/conversation/conversation_starter", {
|
|
@@ -679,6 +686,7 @@ var UserResource = class {
|
|
|
679
686
|
this.c = c;
|
|
680
687
|
this.orgId = orgId;
|
|
681
688
|
}
|
|
689
|
+
/** List users in the organization. */
|
|
682
690
|
async getUsers(queryParams, headers) {
|
|
683
691
|
return extractData(
|
|
684
692
|
this.c.GET("/v1/{organization}/user/", {
|
|
@@ -687,6 +695,7 @@ var UserResource = class {
|
|
|
687
695
|
})
|
|
688
696
|
);
|
|
689
697
|
}
|
|
698
|
+
/** Create (invite) a new user to the organization. */
|
|
690
699
|
async createUser(body, headers) {
|
|
691
700
|
return extractData(
|
|
692
701
|
this.c.POST("/v1/{organization}/user/", {
|
|
@@ -696,6 +705,7 @@ var UserResource = class {
|
|
|
696
705
|
})
|
|
697
706
|
);
|
|
698
707
|
}
|
|
708
|
+
/** Delete a user by ID. */
|
|
699
709
|
async deleteUser(userId, headers) {
|
|
700
710
|
await this.c.DELETE("/v1/{organization}/user/{requested_user_id}", {
|
|
701
711
|
params: { path: { organization: this.orgId, requested_user_id: userId } },
|
|
@@ -703,6 +713,7 @@ var UserResource = class {
|
|
|
703
713
|
});
|
|
704
714
|
return;
|
|
705
715
|
}
|
|
716
|
+
/** Update user information. */
|
|
706
717
|
async updateUser(userId, body, headers) {
|
|
707
718
|
await this.c.POST("/v1/{organization}/user/{requested_user_id}", {
|
|
708
719
|
params: { path: { organization: this.orgId, requested_user_id: userId } },
|
|
@@ -724,6 +735,7 @@ var UserResource = class {
|
|
|
724
735
|
// src/index.ts
|
|
725
736
|
var defaultBaseUrl = "https://api.amigo.ai";
|
|
726
737
|
var AmigoClient = class {
|
|
738
|
+
/** Create a new Amigo client with the given configuration. */
|
|
727
739
|
constructor(config) {
|
|
728
740
|
__publicField(this, "organizations");
|
|
729
741
|
__publicField(this, "conversations");
|