@lightdash-tools/client 0.18.0 → 0.19.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.
@@ -6,7 +6,7 @@ import { BaseApiClient } from '../../base-client';
6
6
  import { type StartConversationThreadBody } from './threads';
7
7
  import type { RequestOptions } from './request-options';
8
8
  import type { HttpClient } from '../../../http/http-client';
9
- import type { AgentSuggestions, AiAgent, AiAgentEvaluation, AiAgentEvaluationRun, AiAgentEvaluationRunSummary, AiAgentEvaluationRunsListResponse, AiAgentEvaluationSummary, AiAgentExploreAccessSummary, AiAgentMcpServerTool, AiAgentsAdminThreadsResult, AiAgentSummary, AiAgentThread, AiAgentThreadMessageVizQuery, AiAgentThreadSummary, AiAgentUserPreferences, AiAgentVerifiedArtifactsListResult, AiAgentVerifiedQuestion, AiArtifact, AiMcpServer, AiMcpServerTool, AiModelOption, AppendEvaluationBody, CloneThreadBody, CreateAgentThreadBody, CreateAgentThreadMessageResult, CreateAiAgent, CreateEvaluationBody, CreateEvaluationResult, CreateProjectMcpServerBody, ExploreAccessSummaryBody, GenerateAgentThreadBody, GenerateAgentThreadResult, GenerateThreadTitleResult, GetAdminThreadsParams, GetAgentSuggestionsParams, GetAiOrganizationSettingsResult, ListVerifiedArtifactsParams, ReadinessScore, SubmitSqlApprovalBody, SubmitSqlApprovalResult, UpdateAiAgent, UpdateAiOrganizationSettings, UpdateAiOrganizationSettingsResult, UpdateAgentMcpServerToolsBody, UpdateEvaluationBody, UpdateMessageFeedbackBody } from '@lightdash-tools/common';
9
+ import type { AgentSuggestions, AiAgent, AiAgentEvaluation, AiAgentEvaluationRun, AiAgentEvaluationRunSummary, AiAgentEvaluationRunsListResponse, AiAgentEvaluationSummary, AiAgentExploreAccessSummary, AiAgentMcpServerTool, AiAgentsAdminThreadsResult, AiAgentSummary, AiAgentThread, AiAgentThreadMessageVizQuery, AiAgentThreadSummary, AiAgentUserPreferences, AiAgentVerifiedArtifactsListResult, AiAgentVerifiedQuestion, AiArtifact, AiMcpServer, AiMcpServerTool, AiModelOption, AiRouterRouteRequest, AiRouterRouteResponseResult, AppendEvaluationBody, CloneThreadBody, CreateAgentThreadBody, CreateAgentThreadMessageResult, CreateAiAgent, CreateEvaluationBody, CreateEvaluationResult, CreateProjectMcpServerBody, ExploreAccessSummaryBody, GenerateAgentThreadBody, GenerateAgentThreadResult, GenerateThreadTitleResult, GetAdminThreadsParams, GetAgentSuggestionsParams, GetAiOrganizationSettingsResult, ListVerifiedArtifactsParams, ReadinessScore, SubmitSqlApprovalBody, SubmitSqlApprovalResult, UpdateAiAgent, UpdateAiOrganizationSettings, UpdateAiOrganizationSettingsResult, UpdateAgentMcpServerToolsBody, UpdateEvaluationBody, UpdateMessageFeedbackBody } from '@lightdash-tools/common';
10
10
  export declare class AiAgentsClient extends BaseApiClient {
11
11
  private readonly admin;
12
12
  private readonly agents;
@@ -16,6 +16,7 @@ export declare class AiAgentsClient extends BaseApiClient {
16
16
  private readonly evaluations;
17
17
  private readonly feedback;
18
18
  private readonly mcpServers;
19
+ private readonly router;
19
20
  private readonly sqlApproval;
20
21
  constructor(http: HttpClient);
21
22
  getAdminThreads(params?: GetAdminThreadsParams): Promise<AiAgentsAdminThreadsResult>;
@@ -39,6 +40,7 @@ export declare class AiAgentsClient extends BaseApiClient {
39
40
  getUserAgentPreferences(projectUuid: string): Promise<AiAgentUserPreferences | null>;
40
41
  setUserAgentPreferences(projectUuid: string, body: AiAgentUserPreferences): Promise<void>;
41
42
  deleteUserAgentPreferences(projectUuid: string): Promise<void>;
43
+ routeAiAgent(body: AiRouterRouteRequest): Promise<AiRouterRouteResponseResult>;
42
44
  listAgentThreads(projectUuid: string, agentUuid: string): Promise<AiAgentThreadSummary[]>;
43
45
  createAgentThread(projectUuid: string, agentUuid: string, body?: CreateAgentThreadBody, options?: RequestOptions): Promise<AiAgentThreadSummary>;
44
46
  getAgentThread(projectUuid: string, agentUuid: string, threadUuid: string, options?: RequestOptions): Promise<AiAgentThread>;
@@ -13,6 +13,7 @@ const discovery_1 = require("./discovery");
13
13
  const evaluations_1 = require("./evaluations");
14
14
  const feedback_1 = require("./feedback");
15
15
  const mcp_servers_1 = require("./mcp-servers");
16
+ const router_1 = require("./router");
16
17
  const sql_approval_1 = require("./sql-approval");
17
18
  const threads_1 = require("./threads");
18
19
  class AiAgentsClient extends base_client_1.BaseApiClient {
@@ -26,6 +27,7 @@ class AiAgentsClient extends base_client_1.BaseApiClient {
26
27
  this.evaluations = new evaluations_1.AiAgentsEvaluationsClient(http);
27
28
  this.feedback = new feedback_1.AiAgentsFeedbackClient(http);
28
29
  this.mcpServers = new mcp_servers_1.AiAgentsMcpServersClient(http);
30
+ this.router = new router_1.AiAgentsRouterClient(http);
29
31
  this.sqlApproval = new sql_approval_1.AiAgentsSqlApprovalClient(http);
30
32
  }
31
33
  // ─── Admin ───────────────────────────────────────────────────────────────────
@@ -82,6 +84,10 @@ class AiAgentsClient extends base_client_1.BaseApiClient {
82
84
  deleteUserAgentPreferences(projectUuid) {
83
85
  return this.discovery.deleteUserAgentPreferences(projectUuid);
84
86
  }
87
+ // ─── AI Router (org-scoped) ──────────────────────────────────────────────────
88
+ routeAiAgent(body) {
89
+ return this.router.routeAiAgent(body);
90
+ }
85
91
  // ─── Project-scoped: threads ─────────────────────────────────────────────────
86
92
  listAgentThreads(projectUuid, agentUuid) {
87
93
  return this.threads.listAgentThreads(projectUuid, agentUuid);
@@ -1,3 +1,4 @@
1
+ import type { RetryConfig } from '../../../config';
1
2
  import type { AxiosRequestConfig } from 'axios';
2
3
  /** Per-request overrides for AI agent thread operations. */
3
4
  export interface RequestOptions {
@@ -7,6 +8,8 @@ export interface RequestOptions {
7
8
  timeoutMs?: number;
8
9
  /** Optional correlation ID sent as `X-Request-Id`. */
9
10
  requestId?: string;
11
+ /** Override the client retry policy for this request (HttpClient 4th argument). */
12
+ retry?: RetryConfig;
10
13
  }
11
- /** Maps {@link RequestOptions} to Axios request config. */
14
+ /** Maps Axios-owned {@link RequestOptions} fields. `retry` is passed separately. */
12
15
  export declare function toAxiosConfig(options?: RequestOptions): AxiosRequestConfig | undefined;
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.toAxiosConfig = toAxiosConfig;
4
- /** Maps {@link RequestOptions} to Axios request config. */
4
+ /** Maps Axios-owned {@link RequestOptions} fields. `retry` is passed separately. */
5
5
  function toAxiosConfig(options) {
6
6
  if (!options) {
7
7
  return undefined;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const request_options_js_1 = require("./request-options.js");
5
+ (0, vitest_1.describe)('toAxiosConfig', () => {
6
+ (0, vitest_1.it)('returns undefined when options are omitted', () => {
7
+ (0, vitest_1.expect)((0, request_options_js_1.toAxiosConfig)()).toBeUndefined();
8
+ (0, vitest_1.expect)((0, request_options_js_1.toAxiosConfig)(undefined)).toBeUndefined();
9
+ });
10
+ (0, vitest_1.it)('maps timeout and request id and ignores retry', () => {
11
+ (0, vitest_1.expect)((0, request_options_js_1.toAxiosConfig)({
12
+ timeoutMs: 180000,
13
+ requestId: 'req-1',
14
+ retry: { maxRetries: 0 },
15
+ })).toEqual({
16
+ timeout: 180000,
17
+ headers: { 'X-Request-Id': 'req-1' },
18
+ });
19
+ });
20
+ (0, vitest_1.it)('returns undefined when only retry is set', () => {
21
+ (0, vitest_1.expect)((0, request_options_js_1.toAxiosConfig)({ retry: { maxRetries: 0 } })).toBeUndefined();
22
+ });
23
+ });
@@ -0,0 +1,10 @@
1
+ /**
2
+ * AI Router API client.
3
+ * Endpoints: /api/v1/org/aiRouter/...
4
+ */
5
+ import { BaseApiClient } from '../../base-client';
6
+ import type { AiRouterRouteRequest, AiRouterRouteResponseResult } from '@lightdash-tools/common';
7
+ export declare class AiAgentsRouterClient extends BaseApiClient {
8
+ /** Route a user prompt to the best accessible agent in the project. */
9
+ routeAiAgent(body: AiRouterRouteRequest): Promise<AiRouterRouteResponseResult>;
10
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ /**
3
+ * AI Router API client.
4
+ * Endpoints: /api/v1/org/aiRouter/...
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.AiAgentsRouterClient = void 0;
8
+ const base_client_1 = require("../../base-client");
9
+ class AiAgentsRouterClient extends base_client_1.BaseApiClient {
10
+ /** Route a user prompt to the best accessible agent in the project. */
11
+ async routeAiAgent(body) {
12
+ return this.http.post('/org/aiRouter/route', body, undefined, {
13
+ maxRetries: 0,
14
+ });
15
+ }
16
+ }
17
+ exports.AiAgentsRouterClient = AiAgentsRouterClient;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const router_1 = require("./router");
5
+ (0, vitest_1.describe)('AiAgentsRouterClient', () => {
6
+ let mockHttp;
7
+ (0, vitest_1.beforeEach)(() => {
8
+ mockHttp = {
9
+ get: vitest_1.vi.fn(),
10
+ post: vitest_1.vi.fn(),
11
+ put: vitest_1.vi.fn(),
12
+ patch: vitest_1.vi.fn(),
13
+ delete: vitest_1.vi.fn(),
14
+ };
15
+ });
16
+ (0, vitest_1.it)('routeAiAgent should call POST /org/aiRouter/route', async () => {
17
+ const client = new router_1.AiAgentsRouterClient(mockHttp);
18
+ const result = {
19
+ nextAction: 'create_thread',
20
+ decision: {
21
+ candidates: [{ agentUuid: 'a1', name: 'Basic', description: null }],
22
+ reasoning: 'best fit',
23
+ confidence: 'high',
24
+ suggestedAgentUuid: 'a1',
25
+ decisionUuid: 'd1',
26
+ },
27
+ };
28
+ vitest_1.vi.mocked(mockHttp.post).mockResolvedValue(result);
29
+ const body = { projectUuid: 'proj1', prompt: 'What is revenue?' };
30
+ const got = await client.routeAiAgent(body);
31
+ (0, vitest_1.expect)(mockHttp.post).toHaveBeenCalledWith('/org/aiRouter/route', body, undefined, {
32
+ maxRetries: 0,
33
+ });
34
+ (0, vitest_1.expect)(got).toEqual(result);
35
+ });
36
+ });
@@ -8,6 +8,8 @@ import type { AiAgentThread, AiAgentThreadSummary, CloneThreadBody, CreateAgentT
8
8
  /** Thread metadata for {@link startConversation}; the user prompt is sent via the message body. */
9
9
  export type StartConversationThreadBody = Omit<CreateAgentThreadBody, 'prompt'>;
10
10
  export declare class AiAgentsThreadsClient extends BaseApiClient {
11
+ private postJson;
12
+ private getJson;
11
13
  /** List all threads for an agent (GET /projects/{projectUuid}/aiAgents/{agentUuid}/threads). */
12
14
  listAgentThreads(projectUuid: string, agentUuid: string): Promise<AiAgentThreadSummary[]>;
13
15
  /**
@@ -27,6 +27,20 @@ function toCreateThreadBody(threadBody) {
27
27
  return body;
28
28
  }
29
29
  class AiAgentsThreadsClient extends base_client_1.BaseApiClient {
30
+ postJson(url, body, options) {
31
+ const axiosConfig = (0, request_options_1.toAxiosConfig)(options);
32
+ if ((options === null || options === void 0 ? void 0 : options.retry) === undefined) {
33
+ return this.http.post(url, body, axiosConfig);
34
+ }
35
+ return this.http.post(url, body, axiosConfig, options.retry);
36
+ }
37
+ getJson(url, options) {
38
+ const axiosConfig = (0, request_options_1.toAxiosConfig)(options);
39
+ if ((options === null || options === void 0 ? void 0 : options.retry) === undefined) {
40
+ return this.http.get(url, axiosConfig);
41
+ }
42
+ return this.http.get(url, axiosConfig, options.retry);
43
+ }
30
44
  /** List all threads for an agent (GET /projects/{projectUuid}/aiAgents/{agentUuid}/threads). */
31
45
  async listAgentThreads(projectUuid, agentUuid) {
32
46
  return this.http.get(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads`);
@@ -37,18 +51,18 @@ class AiAgentsThreadsClient extends base_client_1.BaseApiClient {
37
51
  * {@link generateAgentThreadResponse} for the RFC conversation flow.
38
52
  */
39
53
  async createAgentThread(projectUuid, agentUuid, body, options) {
40
- return this.http.post(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads`, body !== null && body !== void 0 ? body : {}, (0, request_options_1.toAxiosConfig)(options));
54
+ return this.postJson(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads`, body !== null && body !== void 0 ? body : {}, options);
41
55
  }
42
56
  /** Get a thread with its messages (GET …/threads/{threadUuid}). */
43
57
  async getAgentThread(projectUuid, agentUuid, threadUuid, options) {
44
- return this.http.get(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}`, (0, request_options_1.toAxiosConfig)(options));
58
+ return this.getJson(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}`, options);
45
59
  }
46
60
  /**
47
61
  * Add a user message to a thread
48
62
  * (POST …/threads/{threadUuid}/messages).
49
63
  */
50
64
  async createAgentThreadMessage(projectUuid, agentUuid, threadUuid, body, options) {
51
- return this.http.post(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}/messages`, body, (0, request_options_1.toAxiosConfig)(options));
65
+ return this.postJson(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}/messages`, body, options);
52
66
  }
53
67
  async generateAgentThreadResponse(projectUuid, agentUuid, threadUuid, bodyOrOptions, maybeOptions) {
54
68
  const hasPromptBody = bodyOrOptions !== undefined && typeof bodyOrOptions === 'object' && 'prompt' in bodyOrOptions;
@@ -59,7 +73,7 @@ class AiAgentsThreadsClient extends base_client_1.BaseApiClient {
59
73
  return this.generateAgentThreadResponse(projectUuid, agentUuid, threadUuid, options);
60
74
  }
61
75
  const options = (hasPromptBody ? maybeOptions : bodyOrOptions);
62
- return this.http.post(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}/generate`, undefined, (0, request_options_1.toAxiosConfig)(options));
76
+ return this.postJson(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}/generate`, undefined, options);
63
77
  }
64
78
  /**
65
79
  * Start a new conversation: create thread → add user message → generate response.
@@ -80,7 +94,7 @@ class AiAgentsThreadsClient extends base_client_1.BaseApiClient {
80
94
  }
81
95
  /** Generate a title for a thread (POST …/threads/{threadUuid}/generate-title). */
82
96
  async generateThreadTitle(projectUuid, agentUuid, threadUuid, options) {
83
- return this.http.post(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}/generate-title`, undefined, (0, request_options_1.toAxiosConfig)(options));
97
+ return this.postJson(`/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}/generate-title`, undefined, options);
84
98
  }
85
99
  /**
86
100
  * Clone a thread from an existing prompt
@@ -36,4 +36,13 @@ const threads_1 = require("./threads");
36
36
  const client = new threads_1.AiAgentsThreadsClient(mockHttp);
37
37
  await (0, vitest_1.expect)(client.cloneThread('proj1', 'a1', 't1')).rejects.toThrow('cloneThread requires body.promptUuid');
38
38
  });
39
+ (0, vitest_1.it)('passes RequestOptions.retry as the HttpClient retry argument', async () => {
40
+ const client = new threads_1.AiAgentsThreadsClient(mockHttp);
41
+ vitest_1.vi.mocked(mockHttp.post).mockResolvedValue({ response: 'ok' });
42
+ await client.generateAgentThreadResponse('proj1', 'a1', 't1', {
43
+ timeoutMs: 180000,
44
+ retry: { maxRetries: 0 },
45
+ });
46
+ (0, vitest_1.expect)(mockHttp.post).toHaveBeenCalledWith('/projects/proj1/aiAgents/a1/threads/t1/generate', undefined, { timeout: 180000 }, { maxRetries: 0 });
47
+ });
39
48
  });
@@ -2,8 +2,8 @@
2
2
  * HTTP client wrapper: rate limiter + axios + retry.
3
3
  * All requests go through the rate limiter; retry applies to 5xx and network errors.
4
4
  */
5
+ import { type ResolvedLightdashClientConfig, type RetryConfig } from '../config';
5
6
  import { type RateLimiter } from './rate-limiter';
6
- import type { ResolvedLightdashClientConfig } from '../config';
7
7
  import type { AxiosInstance, AxiosRequestConfig } from 'axios';
8
8
  /** Default max raw bytes for chart PNG downloads (8 MiB). */
9
9
  export declare const DEFAULT_BINARY_MAX_BYTES: number;
@@ -30,11 +30,11 @@ export declare class HttpClient {
30
30
  private readonly config;
31
31
  constructor(axiosInstance: AxiosInstance, rateLimiter: RateLimiter, config: ResolvedLightdashClientConfig);
32
32
  private request;
33
- get<T>(url: string, config?: AxiosRequestConfig): Promise<T>;
34
- post<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T>;
35
- put<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T>;
36
- patch<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T>;
37
- delete<T>(url: string, config?: AxiosRequestConfig): Promise<T>;
33
+ get<T>(url: string, config?: AxiosRequestConfig, retry?: RetryConfig): Promise<T>;
34
+ post<T>(url: string, body?: unknown, config?: AxiosRequestConfig, retry?: RetryConfig): Promise<T>;
35
+ put<T>(url: string, body?: unknown, config?: AxiosRequestConfig, retry?: RetryConfig): Promise<T>;
36
+ patch<T>(url: string, body?: unknown, config?: AxiosRequestConfig, retry?: RetryConfig): Promise<T>;
37
+ delete<T>(url: string, config?: AxiosRequestConfig, retry?: RetryConfig): Promise<T>;
38
38
  /**
39
39
  * Fetch raw bytes (no ApiSuccess envelope unwrap). Relative URLs use the
40
40
  * authenticated API client; absolute URLs on a different host (e.g. signed S3)
@@ -106,10 +106,10 @@ class HttpClient {
106
106
  this.rateLimiter = rateLimiter;
107
107
  this.config = config;
108
108
  }
109
- async request(method, url, config) {
109
+ async request(method, url, config, retry) {
110
110
  const doRequest = () => this.axiosInstance.request(Object.assign(Object.assign({}, config), { method,
111
111
  url }));
112
- const response = await this.rateLimiter.schedule(() => (0, retry_1.withRetry)(doRequest, this.config.retry));
112
+ const response = await this.rateLimiter.schedule(() => (0, retry_1.withRetry)(doRequest, retry !== null && retry !== void 0 ? retry : this.config.retry));
113
113
  const data = response.data;
114
114
  if (data !== null && typeof data === 'object') {
115
115
  const envelope = data;
@@ -129,20 +129,20 @@ class HttpClient {
129
129
  message: errors_1.CONTRACT_ERROR_MESSAGE,
130
130
  }, response.config, response);
131
131
  }
132
- async get(url, config) {
133
- return this.request('GET', url, config);
132
+ async get(url, config, retry) {
133
+ return this.request('GET', url, config, retry);
134
134
  }
135
- async post(url, body, config) {
136
- return this.request('POST', url, Object.assign(Object.assign({}, config), { data: body }));
135
+ async post(url, body, config, retry) {
136
+ return this.request('POST', url, Object.assign(Object.assign({}, config), { data: body }), retry);
137
137
  }
138
- async put(url, body, config) {
139
- return this.request('PUT', url, Object.assign(Object.assign({}, config), { data: body }));
138
+ async put(url, body, config, retry) {
139
+ return this.request('PUT', url, Object.assign(Object.assign({}, config), { data: body }), retry);
140
140
  }
141
- async patch(url, body, config) {
142
- return this.request('PATCH', url, Object.assign(Object.assign({}, config), { data: body }));
141
+ async patch(url, body, config, retry) {
142
+ return this.request('PATCH', url, Object.assign(Object.assign({}, config), { data: body }), retry);
143
143
  }
144
- async delete(url, config) {
145
- return this.request('DELETE', url, config);
144
+ async delete(url, config, retry) {
145
+ return this.request('DELETE', url, config, retry);
146
146
  }
147
147
  /**
148
148
  * Fetch raw bytes (no ApiSuccess envelope unwrap). Relative URLs use the
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const http_client_js_1 = require("./http-client.js");
5
+ (0, vitest_1.describe)('HttpClient per-request retry argument', () => {
6
+ function makeClient(requestImpl, retry) {
7
+ const axiosInstance = { request: requestImpl };
8
+ const rateLimiter = {
9
+ schedule: (fn) => fn(),
10
+ };
11
+ const config = {
12
+ baseUrl: 'https://app.lightdash.com',
13
+ timeout: 30000,
14
+ retry,
15
+ };
16
+ return new http_client_js_1.HttpClient(axiosInstance, rateLimiter, config);
17
+ }
18
+ (0, vitest_1.it)('does not retry 5xx when retry.maxRetries is 0', async () => {
19
+ const requestImpl = vitest_1.vi.fn().mockRejectedValue({ response: { status: 500 } });
20
+ const client = makeClient(requestImpl, { maxRetries: 3, retryDelay: 1 });
21
+ await (0, vitest_1.expect)(client.post('/generate', undefined, undefined, { maxRetries: 0 })).rejects.toMatchObject({ response: { status: 500 } });
22
+ (0, vitest_1.expect)(requestImpl).toHaveBeenCalledTimes(1);
23
+ });
24
+ (0, vitest_1.it)('retries 5xx when no per-request retry argument is set', async () => {
25
+ const requestImpl = vitest_1.vi
26
+ .fn()
27
+ .mockRejectedValueOnce({ response: { status: 500 } })
28
+ .mockResolvedValue({
29
+ status: 200,
30
+ data: { status: 'ok', results: { id: 'ok' } },
31
+ config: {},
32
+ });
33
+ const client = makeClient(requestImpl, { maxRetries: 1, retryDelay: 1 });
34
+ await (0, vitest_1.expect)(client.get('/x')).resolves.toEqual({ id: 'ok' });
35
+ (0, vitest_1.expect)(requestImpl).toHaveBeenCalledTimes(2);
36
+ });
37
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lightdash-tools/client",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "Client library for Lightdash AI.",
5
5
  "keywords": [],
6
6
  "repository": {
@@ -15,7 +15,7 @@
15
15
  "dependencies": {
16
16
  "axios": "^1.19.0",
17
17
  "bottleneck": "^2.19.5",
18
- "@lightdash-tools/common": "0.18.0"
18
+ "@lightdash-tools/common": "0.19.0"
19
19
  },
20
20
  "devDependencies": {
21
21
  "@types/node": "^25.9.3"
@@ -12,6 +12,7 @@ import { AiAgentsDiscoveryClient } from './discovery';
12
12
  import { AiAgentsEvaluationsClient } from './evaluations';
13
13
  import { AiAgentsFeedbackClient } from './feedback';
14
14
  import { AiAgentsMcpServersClient } from './mcp-servers';
15
+ import { AiAgentsRouterClient } from './router';
15
16
  import { AiAgentsSqlApprovalClient } from './sql-approval';
16
17
  import { AiAgentsThreadsClient, type StartConversationThreadBody } from './threads';
17
18
 
@@ -39,6 +40,8 @@ import type {
39
40
  AiMcpServer,
40
41
  AiMcpServerTool,
41
42
  AiModelOption,
43
+ AiRouterRouteRequest,
44
+ AiRouterRouteResponseResult,
42
45
  AppendEvaluationBody,
43
46
  CloneThreadBody,
44
47
  CreateAgentThreadBody,
@@ -75,6 +78,7 @@ export class AiAgentsClient extends BaseApiClient {
75
78
  private readonly evaluations: AiAgentsEvaluationsClient;
76
79
  private readonly feedback: AiAgentsFeedbackClient;
77
80
  private readonly mcpServers: AiAgentsMcpServersClient;
81
+ private readonly router: AiAgentsRouterClient;
78
82
  private readonly sqlApproval: AiAgentsSqlApprovalClient;
79
83
 
80
84
  constructor(http: HttpClient) {
@@ -87,6 +91,7 @@ export class AiAgentsClient extends BaseApiClient {
87
91
  this.evaluations = new AiAgentsEvaluationsClient(http);
88
92
  this.feedback = new AiAgentsFeedbackClient(http);
89
93
  this.mcpServers = new AiAgentsMcpServersClient(http);
94
+ this.router = new AiAgentsRouterClient(http);
90
95
  this.sqlApproval = new AiAgentsSqlApprovalClient(http);
91
96
  }
92
97
 
@@ -186,6 +191,12 @@ export class AiAgentsClient extends BaseApiClient {
186
191
  return this.discovery.deleteUserAgentPreferences(projectUuid);
187
192
  }
188
193
 
194
+ // ─── AI Router (org-scoped) ──────────────────────────────────────────────────
195
+
196
+ routeAiAgent(body: AiRouterRouteRequest): Promise<AiRouterRouteResponseResult> {
197
+ return this.router.routeAiAgent(body);
198
+ }
199
+
189
200
  // ─── Project-scoped: threads ─────────────────────────────────────────────────
190
201
 
191
202
  listAgentThreads(projectUuid: string, agentUuid: string): Promise<AiAgentThreadSummary[]> {
@@ -0,0 +1,27 @@
1
+ import { describe, expect, it } from 'vitest';
2
+
3
+ import { toAxiosConfig } from './request-options.js';
4
+
5
+ describe('toAxiosConfig', () => {
6
+ it('returns undefined when options are omitted', () => {
7
+ expect(toAxiosConfig()).toBeUndefined();
8
+ expect(toAxiosConfig(undefined)).toBeUndefined();
9
+ });
10
+
11
+ it('maps timeout and request id and ignores retry', () => {
12
+ expect(
13
+ toAxiosConfig({
14
+ timeoutMs: 180_000,
15
+ requestId: 'req-1',
16
+ retry: { maxRetries: 0 },
17
+ }),
18
+ ).toEqual({
19
+ timeout: 180_000,
20
+ headers: { 'X-Request-Id': 'req-1' },
21
+ });
22
+ });
23
+
24
+ it('returns undefined when only retry is set', () => {
25
+ expect(toAxiosConfig({ retry: { maxRetries: 0 } })).toBeUndefined();
26
+ });
27
+ });
@@ -1,3 +1,4 @@
1
+ import type { RetryConfig } from '../../../config';
1
2
  import type { AxiosRequestConfig } from 'axios';
2
3
 
3
4
  /** Per-request overrides for AI agent thread operations. */
@@ -8,9 +9,11 @@ export interface RequestOptions {
8
9
  timeoutMs?: number;
9
10
  /** Optional correlation ID sent as `X-Request-Id`. */
10
11
  requestId?: string;
12
+ /** Override the client retry policy for this request (HttpClient 4th argument). */
13
+ retry?: RetryConfig;
11
14
  }
12
15
 
13
- /** Maps {@link RequestOptions} to Axios request config. */
16
+ /** Maps Axios-owned {@link RequestOptions} fields. `retry` is passed separately. */
14
17
  export function toAxiosConfig(options?: RequestOptions): AxiosRequestConfig | undefined {
15
18
  if (!options) {
16
19
  return undefined;
@@ -0,0 +1,40 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+
3
+ import { AiAgentsRouterClient } from './router';
4
+
5
+ import type { HttpClient } from '../../../http/http-client';
6
+
7
+ describe('AiAgentsRouterClient', () => {
8
+ let mockHttp: HttpClient;
9
+
10
+ beforeEach(() => {
11
+ mockHttp = {
12
+ get: vi.fn(),
13
+ post: vi.fn(),
14
+ put: vi.fn(),
15
+ patch: vi.fn(),
16
+ delete: vi.fn(),
17
+ } as unknown as HttpClient;
18
+ });
19
+
20
+ it('routeAiAgent should call POST /org/aiRouter/route', async () => {
21
+ const client = new AiAgentsRouterClient(mockHttp);
22
+ const result = {
23
+ nextAction: 'create_thread' as const,
24
+ decision: {
25
+ candidates: [{ agentUuid: 'a1', name: 'Basic', description: null }],
26
+ reasoning: 'best fit',
27
+ confidence: 'high' as const,
28
+ suggestedAgentUuid: 'a1',
29
+ decisionUuid: 'd1',
30
+ },
31
+ };
32
+ vi.mocked(mockHttp.post).mockResolvedValue(result);
33
+ const body = { projectUuid: 'proj1', prompt: 'What is revenue?' };
34
+ const got = await client.routeAiAgent(body);
35
+ expect(mockHttp.post).toHaveBeenCalledWith('/org/aiRouter/route', body, undefined, {
36
+ maxRetries: 0,
37
+ });
38
+ expect(got).toEqual(result);
39
+ });
40
+ });
@@ -0,0 +1,17 @@
1
+ /**
2
+ * AI Router API client.
3
+ * Endpoints: /api/v1/org/aiRouter/...
4
+ */
5
+
6
+ import { BaseApiClient } from '../../base-client';
7
+
8
+ import type { AiRouterRouteRequest, AiRouterRouteResponseResult } from '@lightdash-tools/common';
9
+
10
+ export class AiAgentsRouterClient extends BaseApiClient {
11
+ /** Route a user prompt to the best accessible agent in the project. */
12
+ async routeAiAgent(body: AiRouterRouteRequest): Promise<AiRouterRouteResponseResult> {
13
+ return this.http.post<AiRouterRouteResponseResult>('/org/aiRouter/route', body, undefined, {
14
+ maxRetries: 0,
15
+ });
16
+ }
17
+ }
@@ -52,4 +52,19 @@ describe('AiAgentsThreadsClient extensions', () => {
52
52
  'cloneThread requires body.promptUuid',
53
53
  );
54
54
  });
55
+
56
+ it('passes RequestOptions.retry as the HttpClient retry argument', async () => {
57
+ const client = new AiAgentsThreadsClient(mockHttp);
58
+ vi.mocked(mockHttp.post).mockResolvedValue({ response: 'ok' });
59
+ await client.generateAgentThreadResponse('proj1', 'a1', 't1', {
60
+ timeoutMs: 180_000,
61
+ retry: { maxRetries: 0 },
62
+ });
63
+ expect(mockHttp.post).toHaveBeenCalledWith(
64
+ '/projects/proj1/aiAgents/a1/threads/t1/generate',
65
+ undefined,
66
+ { timeout: 180_000 },
67
+ { maxRetries: 0 },
68
+ );
69
+ });
55
70
  });
@@ -34,6 +34,22 @@ function toCreateThreadBody(
34
34
  }
35
35
 
36
36
  export class AiAgentsThreadsClient extends BaseApiClient {
37
+ private postJson<T>(url: string, body: unknown, options?: RequestOptions): Promise<T> {
38
+ const axiosConfig = toAxiosConfig(options);
39
+ if (options?.retry === undefined) {
40
+ return this.http.post<T>(url, body, axiosConfig);
41
+ }
42
+ return this.http.post<T>(url, body, axiosConfig, options.retry);
43
+ }
44
+
45
+ private getJson<T>(url: string, options?: RequestOptions): Promise<T> {
46
+ const axiosConfig = toAxiosConfig(options);
47
+ if (options?.retry === undefined) {
48
+ return this.http.get<T>(url, axiosConfig);
49
+ }
50
+ return this.http.get<T>(url, axiosConfig, options.retry);
51
+ }
52
+
37
53
  /** List all threads for an agent (GET /projects/{projectUuid}/aiAgents/{agentUuid}/threads). */
38
54
  async listAgentThreads(projectUuid: string, agentUuid: string): Promise<AiAgentThreadSummary[]> {
39
55
  return this.http.get<AiAgentThreadSummary[]>(
@@ -52,10 +68,10 @@ export class AiAgentsThreadsClient extends BaseApiClient {
52
68
  body?: CreateAgentThreadBody,
53
69
  options?: RequestOptions,
54
70
  ): Promise<AiAgentThreadSummary> {
55
- return this.http.post<AiAgentThreadSummary>(
71
+ return this.postJson<AiAgentThreadSummary>(
56
72
  `/projects/${projectUuid}/aiAgents/${agentUuid}/threads`,
57
73
  body ?? {},
58
- toAxiosConfig(options),
74
+ options,
59
75
  );
60
76
  }
61
77
 
@@ -66,9 +82,9 @@ export class AiAgentsThreadsClient extends BaseApiClient {
66
82
  threadUuid: string,
67
83
  options?: RequestOptions,
68
84
  ): Promise<AiAgentThread> {
69
- return this.http.get<AiAgentThread>(
85
+ return this.getJson<AiAgentThread>(
70
86
  `/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}`,
71
- toAxiosConfig(options),
87
+ options,
72
88
  );
73
89
  }
74
90
 
@@ -83,10 +99,10 @@ export class AiAgentsThreadsClient extends BaseApiClient {
83
99
  body: GenerateAgentThreadBody,
84
100
  options?: RequestOptions,
85
101
  ): Promise<CreateAgentThreadMessageResult> {
86
- return this.http.post<CreateAgentThreadMessageResult>(
102
+ return this.postJson<CreateAgentThreadMessageResult>(
87
103
  `/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}/messages`,
88
104
  body,
89
- toAxiosConfig(options),
105
+ options,
90
106
  );
91
107
  }
92
108
 
@@ -131,10 +147,10 @@ export class AiAgentsThreadsClient extends BaseApiClient {
131
147
  }
132
148
 
133
149
  const options = (hasPromptBody ? maybeOptions : bodyOrOptions) as RequestOptions | undefined;
134
- return this.http.post<GenerateAgentThreadResult>(
150
+ return this.postJson<GenerateAgentThreadResult>(
135
151
  `/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}/generate`,
136
152
  undefined,
137
- toAxiosConfig(options),
153
+ options,
138
154
  );
139
155
  }
140
156
 
@@ -185,10 +201,10 @@ export class AiAgentsThreadsClient extends BaseApiClient {
185
201
  threadUuid: string,
186
202
  options?: RequestOptions,
187
203
  ): Promise<GenerateThreadTitleResult> {
188
- return this.http.post<GenerateThreadTitleResult>(
204
+ return this.postJson<GenerateThreadTitleResult>(
189
205
  `/projects/${projectUuid}/aiAgents/${agentUuid}/threads/${threadUuid}/generate-title`,
190
206
  undefined,
191
- toAxiosConfig(options),
207
+ options,
192
208
  );
193
209
  }
194
210
 
@@ -0,0 +1,45 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import { HttpClient } from './http-client.js';
4
+
5
+ import type { ResolvedLightdashClientConfig, RetryConfig } from '../config.js';
6
+ import type { RateLimiter } from './rate-limiter.js';
7
+ import type { AxiosInstance } from 'axios';
8
+
9
+ describe('HttpClient per-request retry argument', () => {
10
+ function makeClient(requestImpl: ReturnType<typeof vi.fn>, retry: RetryConfig) {
11
+ const axiosInstance = { request: requestImpl } as unknown as AxiosInstance;
12
+ const rateLimiter = {
13
+ schedule: <T>(fn: () => Promise<T>) => fn(),
14
+ } as unknown as RateLimiter;
15
+ const config = {
16
+ baseUrl: 'https://app.lightdash.com',
17
+ timeout: 30_000,
18
+ retry,
19
+ } as unknown as ResolvedLightdashClientConfig;
20
+ return new HttpClient(axiosInstance, rateLimiter, config);
21
+ }
22
+
23
+ it('does not retry 5xx when retry.maxRetries is 0', async () => {
24
+ const requestImpl = vi.fn().mockRejectedValue({ response: { status: 500 } });
25
+ const client = makeClient(requestImpl, { maxRetries: 3, retryDelay: 1 });
26
+ await expect(
27
+ client.post('/generate', undefined, undefined, { maxRetries: 0 }),
28
+ ).rejects.toMatchObject({ response: { status: 500 } });
29
+ expect(requestImpl).toHaveBeenCalledTimes(1);
30
+ });
31
+
32
+ it('retries 5xx when no per-request retry argument is set', async () => {
33
+ const requestImpl = vi
34
+ .fn()
35
+ .mockRejectedValueOnce({ response: { status: 500 } })
36
+ .mockResolvedValue({
37
+ status: 200,
38
+ data: { status: 'ok', results: { id: 'ok' } },
39
+ config: {},
40
+ });
41
+ const client = makeClient(requestImpl, { maxRetries: 1, retryDelay: 1 });
42
+ await expect(client.get('/x')).resolves.toEqual({ id: 'ok' });
43
+ expect(requestImpl).toHaveBeenCalledTimes(2);
44
+ });
45
+ });
@@ -5,7 +5,7 @@
5
5
 
6
6
  import axios from 'axios';
7
7
 
8
- import { DEFAULT_TIMEOUT } from '../config';
8
+ import { DEFAULT_TIMEOUT, type ResolvedLightdashClientConfig, type RetryConfig } from '../config';
9
9
  import {
10
10
  type ApiErrorPayload,
11
11
  BinarySizeLimitError,
@@ -19,7 +19,6 @@ import { withRetry } from '../utils/retry';
19
19
  import { type RateLimiter } from './rate-limiter';
20
20
  import { isApiSuccessEnvelope, type ApiEnvelope } from './unwrap-api-success';
21
21
 
22
- import type { ResolvedLightdashClientConfig } from '../config';
23
22
  import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, Method } from 'axios';
24
23
 
25
24
  /** Default max raw bytes for chart PNG downloads (8 MiB). */
@@ -144,7 +143,12 @@ export class HttpClient {
144
143
  private readonly config: ResolvedLightdashClientConfig,
145
144
  ) {}
146
145
 
147
- private async request<T>(method: Method, url: string, config?: AxiosRequestConfig): Promise<T> {
146
+ private async request<T>(
147
+ method: Method,
148
+ url: string,
149
+ config?: AxiosRequestConfig,
150
+ retry?: RetryConfig,
151
+ ): Promise<T> {
148
152
  const doRequest = () =>
149
153
  this.axiosInstance.request<ApiEnvelope<T>>({
150
154
  ...config,
@@ -152,7 +156,9 @@ export class HttpClient {
152
156
  url,
153
157
  });
154
158
 
155
- const response = await this.rateLimiter.schedule(() => withRetry(doRequest, this.config.retry));
159
+ const response = await this.rateLimiter.schedule(() =>
160
+ withRetry(doRequest, retry ?? this.config.retry),
161
+ );
156
162
 
157
163
  const data = response.data;
158
164
  if (data !== null && typeof data === 'object') {
@@ -186,24 +192,39 @@ export class HttpClient {
186
192
  );
187
193
  }
188
194
 
189
- async get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
190
- return this.request<T>('GET', url, config);
195
+ async get<T>(url: string, config?: AxiosRequestConfig, retry?: RetryConfig): Promise<T> {
196
+ return this.request<T>('GET', url, config, retry);
191
197
  }
192
198
 
193
- async post<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T> {
194
- return this.request<T>('POST', url, { ...config, data: body });
199
+ async post<T>(
200
+ url: string,
201
+ body?: unknown,
202
+ config?: AxiosRequestConfig,
203
+ retry?: RetryConfig,
204
+ ): Promise<T> {
205
+ return this.request<T>('POST', url, { ...config, data: body }, retry);
195
206
  }
196
207
 
197
- async put<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T> {
198
- return this.request<T>('PUT', url, { ...config, data: body });
208
+ async put<T>(
209
+ url: string,
210
+ body?: unknown,
211
+ config?: AxiosRequestConfig,
212
+ retry?: RetryConfig,
213
+ ): Promise<T> {
214
+ return this.request<T>('PUT', url, { ...config, data: body }, retry);
199
215
  }
200
216
 
201
- async patch<T>(url: string, body?: unknown, config?: AxiosRequestConfig): Promise<T> {
202
- return this.request<T>('PATCH', url, { ...config, data: body });
217
+ async patch<T>(
218
+ url: string,
219
+ body?: unknown,
220
+ config?: AxiosRequestConfig,
221
+ retry?: RetryConfig,
222
+ ): Promise<T> {
223
+ return this.request<T>('PATCH', url, { ...config, data: body }, retry);
203
224
  }
204
225
 
205
- async delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
206
- return this.request<T>('DELETE', url, config);
226
+ async delete<T>(url: string, config?: AxiosRequestConfig, retry?: RetryConfig): Promise<T> {
227
+ return this.request<T>('DELETE', url, config, retry);
207
228
  }
208
229
 
209
230
  /**