@vertesia/client 1.6.0-dev.20261022.120426Z → 1.7.0-dev.20261120.100641Z

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/lib/AccountApi.d.ts +2 -0
  2. package/lib/AccountApi.d.ts.map +1 -1
  3. package/lib/AccountApi.js +3 -0
  4. package/lib/AccountApi.js.map +1 -1
  5. package/lib/AccountRolesApi.d.ts +11 -0
  6. package/lib/AccountRolesApi.d.ts.map +1 -0
  7. package/lib/AccountRolesApi.js +22 -0
  8. package/lib/AccountRolesApi.js.map +1 -0
  9. package/lib/AppsApi.d.ts +18 -3
  10. package/lib/AppsApi.d.ts.map +1 -1
  11. package/lib/AppsApi.js +34 -4
  12. package/lib/AppsApi.js.map +1 -1
  13. package/lib/AuditTrailApi.d.ts +6 -1
  14. package/lib/AuditTrailApi.d.ts.map +1 -1
  15. package/lib/AuditTrailApi.js +8 -0
  16. package/lib/AuditTrailApi.js.map +1 -1
  17. package/lib/EnvironmentsApi.d.ts +2 -2
  18. package/lib/EnvironmentsApi.d.ts.map +1 -1
  19. package/lib/IamApi.d.ts +1 -1
  20. package/lib/IamApi.js +1 -1
  21. package/lib/InteractionCatalogApi.d.ts +19 -1
  22. package/lib/InteractionCatalogApi.d.ts.map +1 -1
  23. package/lib/InteractionCatalogApi.js +30 -0
  24. package/lib/InteractionCatalogApi.js.map +1 -1
  25. package/lib/InteractionsApi.d.ts +3 -12
  26. package/lib/InteractionsApi.d.ts.map +1 -1
  27. package/lib/InteractionsApi.js +2 -23
  28. package/lib/InteractionsApi.js.map +1 -1
  29. package/lib/OAuthClientsApi.d.ts +3 -1
  30. package/lib/OAuthClientsApi.d.ts.map +1 -1
  31. package/lib/OAuthClientsApi.js +4 -0
  32. package/lib/OAuthClientsApi.js.map +1 -1
  33. package/lib/OAuthProvidersApi.d.ts +6 -2
  34. package/lib/OAuthProvidersApi.d.ts.map +1 -1
  35. package/lib/OAuthProvidersApi.js +6 -2
  36. package/lib/OAuthProvidersApi.js.map +1 -1
  37. package/lib/RemoteMcpConnectionsApi.d.ts +5 -1
  38. package/lib/RemoteMcpConnectionsApi.d.ts.map +1 -1
  39. package/lib/RemoteMcpConnectionsApi.js +6 -2
  40. package/lib/RemoteMcpConnectionsApi.js.map +1 -1
  41. package/lib/StreamSource.d.ts +19 -1
  42. package/lib/StreamSource.d.ts.map +1 -1
  43. package/lib/StreamSource.js +31 -1
  44. package/lib/StreamSource.js.map +1 -1
  45. package/lib/UsersApi.d.ts +7 -1
  46. package/lib/UsersApi.d.ts.map +1 -1
  47. package/lib/UsersApi.js +8 -0
  48. package/lib/UsersApi.js.map +1 -1
  49. package/lib/client.d.ts +14 -2
  50. package/lib/client.d.ts.map +1 -1
  51. package/lib/client.js +57 -8
  52. package/lib/client.js.map +1 -1
  53. package/lib/execute.d.ts.map +1 -1
  54. package/lib/execute.js +4 -2
  55. package/lib/execute.js.map +1 -1
  56. package/lib/idempotency-key.d.ts +19 -0
  57. package/lib/idempotency-key.d.ts.map +1 -0
  58. package/lib/idempotency-key.js +34 -0
  59. package/lib/idempotency-key.js.map +1 -0
  60. package/lib/nodejs/NodeStreamSource.d.ts +10 -1
  61. package/lib/nodejs/NodeStreamSource.d.ts.map +1 -1
  62. package/lib/nodejs/NodeStreamSource.js +40 -2
  63. package/lib/nodejs/NodeStreamSource.js.map +1 -1
  64. package/lib/store/AgentsApi.d.ts.map +1 -1
  65. package/lib/store/AgentsApi.js +5 -2
  66. package/lib/store/AgentsApi.js.map +1 -1
  67. package/lib/store/ContentSourcesApi.d.ts +57 -0
  68. package/lib/store/ContentSourcesApi.d.ts.map +1 -0
  69. package/lib/store/ContentSourcesApi.js +92 -0
  70. package/lib/store/ContentSourcesApi.js.map +1 -0
  71. package/lib/store/CostApi.d.ts +9 -1
  72. package/lib/store/CostApi.d.ts.map +1 -1
  73. package/lib/store/CostApi.js +16 -0
  74. package/lib/store/CostApi.js.map +1 -1
  75. package/lib/store/DashboardApi.d.ts +61 -19
  76. package/lib/store/DashboardApi.d.ts.map +1 -1
  77. package/lib/store/DashboardApi.js +75 -19
  78. package/lib/store/DashboardApi.js.map +1 -1
  79. package/lib/store/DataApi.d.ts +9 -9
  80. package/lib/store/DataApi.d.ts.map +1 -1
  81. package/lib/store/DataApi.js +14 -10
  82. package/lib/store/DataApi.js.map +1 -1
  83. package/lib/store/FilesApi.d.ts +15 -1
  84. package/lib/store/FilesApi.d.ts.map +1 -1
  85. package/lib/store/FilesApi.js +54 -75
  86. package/lib/store/FilesApi.js.map +1 -1
  87. package/lib/store/NotificationsApi.d.ts +39 -0
  88. package/lib/store/NotificationsApi.d.ts.map +1 -0
  89. package/lib/store/NotificationsApi.js +68 -0
  90. package/lib/store/NotificationsApi.js.map +1 -0
  91. package/lib/store/ObjectsApi.d.ts +6 -1
  92. package/lib/store/ObjectsApi.d.ts.map +1 -1
  93. package/lib/store/ObjectsApi.js +23 -30
  94. package/lib/store/ObjectsApi.js.map +1 -1
  95. package/lib/store/RenderingApi.d.ts.map +1 -1
  96. package/lib/store/RenderingApi.js +1 -0
  97. package/lib/store/RenderingApi.js.map +1 -1
  98. package/lib/store/WorkflowsApi.d.ts +19 -1
  99. package/lib/store/WorkflowsApi.d.ts.map +1 -1
  100. package/lib/store/WorkflowsApi.js +21 -0
  101. package/lib/store/WorkflowsApi.js.map +1 -1
  102. package/lib/store/chunked-upload.d.ts +71 -0
  103. package/lib/store/chunked-upload.d.ts.map +1 -0
  104. package/lib/store/chunked-upload.js +206 -0
  105. package/lib/store/chunked-upload.js.map +1 -0
  106. package/lib/store/client.d.ts +9 -1
  107. package/lib/store/client.d.ts.map +1 -1
  108. package/lib/store/client.js +17 -1
  109. package/lib/store/client.js.map +1 -1
  110. package/lib/store/index.d.ts +3 -0
  111. package/lib/store/index.d.ts.map +1 -1
  112. package/lib/store/index.js +3 -0
  113. package/lib/store/index.js.map +1 -1
  114. package/lib/store/node-request.browser.d.ts +14 -0
  115. package/lib/store/node-request.browser.d.ts.map +1 -0
  116. package/lib/store/node-request.browser.js +20 -0
  117. package/lib/store/node-request.browser.js.map +1 -0
  118. package/lib/store/node-request.d.ts +20 -0
  119. package/lib/store/node-request.d.ts.map +1 -0
  120. package/lib/store/node-request.js +116 -0
  121. package/lib/store/node-request.js.map +1 -0
  122. package/lib/store/node-sessions.browser.d.ts +3 -0
  123. package/lib/store/node-sessions.browser.d.ts.map +1 -0
  124. package/lib/store/node-sessions.browser.js +15 -0
  125. package/lib/store/node-sessions.browser.js.map +1 -0
  126. package/lib/store/node-sessions.d.ts +14 -0
  127. package/lib/store/node-sessions.d.ts.map +1 -0
  128. package/lib/store/node-sessions.js +88 -0
  129. package/lib/store/node-sessions.js.map +1 -0
  130. package/lib/store/signed-url.d.ts +12 -16
  131. package/lib/store/signed-url.d.ts.map +1 -1
  132. package/lib/store/signed-url.js +111 -71
  133. package/lib/store/signed-url.js.map +1 -1
  134. package/lib/store/stream-bytes.d.ts +16 -0
  135. package/lib/store/stream-bytes.d.ts.map +1 -0
  136. package/lib/store/stream-bytes.js +70 -0
  137. package/lib/store/stream-bytes.js.map +1 -0
  138. package/lib/store/stream-termination.d.ts.map +1 -1
  139. package/lib/store/stream-termination.js +17 -16
  140. package/lib/store/stream-termination.js.map +1 -1
  141. package/lib/store/upload-body.d.ts +21 -0
  142. package/lib/store/upload-body.d.ts.map +1 -0
  143. package/lib/store/upload-body.js +32 -0
  144. package/lib/store/upload-body.js.map +1 -0
  145. package/lib/store/upload-content.d.ts +21 -0
  146. package/lib/store/upload-content.d.ts.map +1 -0
  147. package/lib/store/upload-content.js +113 -0
  148. package/lib/store/upload-content.js.map +1 -0
  149. package/lib/store/upload-runtime.d.ts +21 -0
  150. package/lib/store/upload-runtime.d.ts.map +1 -0
  151. package/lib/store/upload-runtime.js +40 -0
  152. package/lib/store/upload-runtime.js.map +1 -0
  153. package/lib/user-agent.d.ts +11 -0
  154. package/lib/user-agent.d.ts.map +1 -0
  155. package/lib/user-agent.js +35 -0
  156. package/lib/user-agent.js.map +1 -0
  157. package/lib/vertesia-client.js +10 -9
  158. package/lib/vertesia-client.js.map +1 -1
  159. package/package.json +35 -11
  160. package/src/AccountApi.ts +3 -0
  161. package/src/AccountRolesApi.ts +29 -0
  162. package/src/AppsApi.ts +58 -4
  163. package/src/AuditTrailApi.ts +11 -0
  164. package/src/EnvironmentsApi.ts +2 -2
  165. package/src/IamApi.ts +1 -1
  166. package/src/InteractionCatalogApi.ts +44 -1
  167. package/src/InteractionsApi.ts +2 -31
  168. package/src/OAuthClientsApi.ts +6 -0
  169. package/src/OAuthProvidersApi.ts +7 -2
  170. package/src/RemoteMcpConnectionsApi.ts +7 -3
  171. package/src/StreamSource.ts +29 -0
  172. package/src/UsersApi.ts +10 -1
  173. package/src/client.ts +74 -8
  174. package/src/execute.ts +4 -2
  175. package/src/idempotency-key.ts +34 -0
  176. package/src/nodejs/NodeStreamSource.ts +37 -2
  177. package/src/store/AgentsApi.ts +5 -2
  178. package/src/store/ContentSourcesApi.ts +135 -0
  179. package/src/store/CostApi.ts +24 -0
  180. package/src/store/DashboardApi.ts +93 -18
  181. package/src/store/DataApi.ts +14 -10
  182. package/src/store/FilesApi.ts +84 -78
  183. package/src/store/NotificationsApi.ts +103 -0
  184. package/src/store/ObjectsApi.ts +30 -34
  185. package/src/store/RenderingApi.ts +1 -0
  186. package/src/store/WorkflowsApi.ts +25 -0
  187. package/src/store/chunked-upload.ts +272 -0
  188. package/src/store/client.ts +23 -1
  189. package/src/store/index.ts +3 -0
  190. package/src/store/node-request.browser.ts +22 -0
  191. package/src/store/node-request.ts +120 -0
  192. package/src/store/node-sessions.browser.ts +16 -0
  193. package/src/store/node-sessions.ts +109 -0
  194. package/src/store/signed-url.ts +126 -72
  195. package/src/store/stream-bytes.ts +79 -0
  196. package/src/store/stream-termination.ts +24 -24
  197. package/src/store/upload-body.ts +37 -0
  198. package/src/store/upload-content.ts +129 -0
  199. package/src/store/upload-runtime.ts +42 -0
  200. package/src/user-agent.ts +41 -0
package/src/client.ts CHANGED
@@ -1,6 +1,18 @@
1
- import { AbstractFetchClient, type FETCH_FN, type IRequestRetryPolicy } from '@vertesia/api-fetch-client';
1
+ import {
2
+ AbstractFetchClient,
3
+ type FETCH_FN,
4
+ type IPacingRetryPolicy,
5
+ type IRequestRetryPolicy,
6
+ type RequestIdentityProvider,
7
+ } from '@vertesia/api-fetch-client';
2
8
  import type { AppSessionTokenRequest, AppSessionTokenResponse } from '@vertesia/common';
3
- import { APP_VERSION_HEADER, type AuthTokenPayload, type AuthTokenResponse } from '@vertesia/common';
9
+ import {
10
+ APP_VERSION_HEADER,
11
+ type AuthTokenPayload,
12
+ type AuthTokenResponse,
13
+ type ContentSecurity,
14
+ } from '@vertesia/common';
15
+ import { resolveAbacClaim, TokenClaimReferenceError } from '@vertesia/studio-utils/token-claims';
4
16
  import AccountApi from './AccountApi.js';
5
17
  import AccountsApi from './AccountsApi.js';
6
18
  import AnalyticsApi from './AnalyticsApi.js';
@@ -33,6 +45,7 @@ import ToolsApi from './ToolsApi.js';
33
45
  import TrainingApi from './TrainingApi.js';
34
46
  import UsersApi from './UsersApi.js';
35
47
  import { warnUnknownOptions } from './unknown-options.js';
48
+ import { clientUserAgentHeaders } from './user-agent.js';
36
49
  import ViewsApi from './ViewsApi.js';
37
50
 
38
51
  /**
@@ -68,10 +81,14 @@ export type VertesiaClientProps = {
68
81
  storeUrl?: string;
69
82
  tokenServerUrl?: string;
70
83
  apikey?: string;
84
+ /** Supplies the complete Authorization header; takes precedence over apikey. */
85
+ authCallback?: () => Promise<string>;
71
86
  sessionTags?: string | string[];
87
+ requestIdentity?: RequestIdentityProvider;
72
88
  onRequest?: (request: Request) => void;
73
89
  onResponse?: (response: Response) => void;
74
90
  retryPolicy?: IRequestRetryPolicy;
91
+ pacingRetry?: IPacingRetryPolicy | false;
75
92
  /**
76
93
  * Default request timeout in ms applied to every request (studio + store) unless overridden
77
94
  * per-request via `timeoutMs`. `false`/`null`/`0` disables it. Aborts the whole request
@@ -92,10 +109,13 @@ const KNOWN_CLIENT_OPTIONS: Record<keyof Required<VertesiaClientProps>, true> =
92
109
  storeUrl: true,
93
110
  tokenServerUrl: true,
94
111
  apikey: true,
112
+ authCallback: true,
95
113
  sessionTags: true,
114
+ requestIdentity: true,
96
115
  onRequest: true,
97
116
  onResponse: true,
98
117
  retryPolicy: true,
118
+ pacingRetry: true,
99
119
  timeout: true,
100
120
  fetch: true,
101
121
  };
@@ -105,6 +125,7 @@ export class VertesiaClient extends AbstractFetchClient<VertesiaClient> {
105
125
  * The JWT token linked to the API KEY (sk or pk)
106
126
  */
107
127
  _jwt: string | null = null;
128
+ private abacResolution?: { jwt: string; value: Promise<ContentSecurity | undefined> };
108
129
 
109
130
  /**
110
131
  * The store client
@@ -230,9 +251,12 @@ export class VertesiaClient extends AbstractFetchClient<VertesiaClient> {
230
251
  serverUrl: zenoServerUrl,
231
252
  tokenServerUrl: this.tokenServerUrl,
232
253
  apikey: opts.apikey,
254
+ authCallback: opts.authCallback,
255
+ requestIdentity: opts.requestIdentity,
233
256
  onRequest: opts.onRequest,
234
257
  onResponse: opts.onResponse,
235
258
  retryPolicy: opts.retryPolicy,
259
+ pacingRetry: opts.pacingRetry,
236
260
  timeout: opts.timeout,
237
261
  fetch: opts.fetch,
238
262
  });
@@ -242,14 +266,21 @@ export class VertesiaClient extends AbstractFetchClient<VertesiaClient> {
242
266
  this.withRetryPolicy(opts.retryPolicy);
243
267
  }
244
268
 
269
+ if (opts.pacingRetry !== undefined) {
270
+ this.withPacingRetry(opts.pacingRetry);
271
+ }
272
+
245
273
  if (opts.timeout !== undefined) {
246
274
  this.withTimeout(opts.timeout);
247
275
  }
248
276
 
249
- if (opts.apikey) {
277
+ if (opts.authCallback) {
278
+ this.withAuthCallback(opts.authCallback);
279
+ } else if (opts.apikey) {
250
280
  void this.withApiKey(opts.apikey);
251
281
  }
252
282
 
283
+ this.requestIdentity = opts.requestIdentity;
253
284
  this.onRequest = opts.onRequest;
254
285
  this.onResponse = opts.onResponse;
255
286
  this.sessionTags = opts.sessionTags;
@@ -325,12 +356,9 @@ export class VertesiaClient extends AbstractFetchClient<VertesiaClient> {
325
356
  }
326
357
 
327
358
  async getRawJWT() {
328
- if (!this._jwt && this._auth) {
359
+ if (this._auth) {
329
360
  const auth = await this._auth();
330
- if (!this._jwt) {
331
- // the _jwt may be set by the auth callback
332
- this._jwt = auth.trim().split(' ')[1]; // remove Bearer prefix
333
- }
361
+ this._jwt = auth.trim().split(' ')[1]; // remove Bearer prefix
334
362
  }
335
363
  return this._jwt || null;
336
364
  }
@@ -340,6 +368,38 @@ export class VertesiaClient extends AbstractFetchClient<VertesiaClient> {
340
368
  return jwt ? decodeJWT(jwt) : null;
341
369
  }
342
370
 
371
+ /**
372
+ * Resolve ABAC only when it is needed. JWT decoding alone deliberately keeps opaque claim
373
+ * references intact. The existing STS validation endpoint verifies the complete bearer before
374
+ * loading Redis; knowing a reference alone never authorizes reading its policy.
375
+ */
376
+ async getAbac(): Promise<ContentSecurity | undefined> {
377
+ const jwt = await this.getRawJWT();
378
+ if (!jwt) return undefined;
379
+ if (this.abacResolution?.jwt === jwt) return this.abacResolution.value;
380
+
381
+ const payload = decodeJWT(jwt);
382
+ const value = resolveAbacClaim(payload.abac ?? payload.content_security, async () => {
383
+ const response = await this.post<{ valid: boolean; payload?: AuthTokenPayload }>(
384
+ new URL('/validate', this.tokenServerUrl).toString(),
385
+ { payload: { token: jwt } },
386
+ );
387
+ const abac = response.payload?.abac;
388
+ if (!response.valid || !abac || typeof abac !== 'object' || Array.isArray(abac)) {
389
+ throw new TokenClaimReferenceError('STS could not resolve token authorization context');
390
+ }
391
+ return { abac };
392
+ });
393
+ const entry = { jwt, value };
394
+ this.abacResolution = entry;
395
+ try {
396
+ return await value;
397
+ } catch (error: unknown) {
398
+ if (this.abacResolution === entry) this.abacResolution = undefined;
399
+ throw error;
400
+ }
401
+ }
402
+
343
403
  async getProject() {
344
404
  const jwt = await this.getDecodedJWT();
345
405
  return jwt?.project || null;
@@ -375,6 +435,10 @@ export class VertesiaClient extends AbstractFetchClient<VertesiaClient> {
375
435
  return this.store.files;
376
436
  }
377
437
 
438
+ get contentSources() {
439
+ return this.store.contentSources;
440
+ }
441
+
378
442
  get processes() {
379
443
  return this.store.processes;
380
444
  }
@@ -442,6 +506,7 @@ export class VertesiaClient extends AbstractFetchClient<VertesiaClient> {
442
506
  get initialHeaders() {
443
507
  return {
444
508
  ...super.initialHeaders,
509
+ ...clientUserAgentHeaders(),
445
510
  [VERSION_HEADER]: VERSION,
446
511
  };
447
512
  }
@@ -507,6 +572,7 @@ export function decodeJWT(jwt: string): AuthTokenPayload {
507
572
  throw new Error(`Invalid auth token: payload segment is not base64url (${(err as Error).message})`);
508
573
  }
509
574
 
575
+ // Decoding is not authentication; servers verify the signature and permission contract.
510
576
  try {
511
577
  return JSON.parse(decodedJson);
512
578
  } catch {
package/src/execute.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  type RateLimitRequestResponse,
12
12
  } from '@vertesia/common';
13
13
  import type { VertesiaClient } from './client.js';
14
+ import { withIdempotencyKey } from './idempotency-key.js';
14
15
 
15
16
  /**
16
17
  * Client-side timeout for a synchronous (non-streaming) interaction execution. The request blocks on
@@ -192,9 +193,10 @@ export async function executeInteractionAsync(
192
193
  // A conversation starts an agent run: without `idempotency_key` a replay could start a second one,
193
194
  // so opt out of any client-level retry policy (see `AgentsApi.start`). With a key, a replay
194
195
  // returns the run the first request started.
195
- const unkeyedConversation = payload.type === 'conversation' && !payload.idempotency_key;
196
+ const keyedPayload = payload.type === 'conversation' ? withIdempotencyKey(client, payload) : payload;
197
+ const unkeyedConversation = keyedPayload.type === 'conversation' && !keyedPayload.idempotency_key;
196
198
  return await client.post('/api/v1/execute/async', {
197
- payload,
199
+ payload: keyedPayload,
198
200
  retryPolicy: unkeyedConversation ? false : undefined,
199
201
  });
200
202
  }
@@ -0,0 +1,34 @@
1
+ import { type ClientBase, generateIdempotencyKey } from '@vertesia/api-fetch-client';
2
+
3
+ /**
4
+ * Give a create request its own `idempotency_key` when the client's retry policy asks for idempotency
5
+ * keys and the caller set none, so a retried attempt returns what the first one created instead of
6
+ * creating it again. The server stores the key with the resource it creates. A caller's key, or a
7
+ * client without the opt-in, leaves the payload unchanged.
8
+ */
9
+ export function withIdempotencyKey<T extends { idempotency_key?: string }>(client: ClientBase, payload: T): T {
10
+ if (payload.idempotency_key || !client.getRetryPolicy()?.idempotencyKeys) {
11
+ return payload;
12
+ }
13
+ return {
14
+ ...payload,
15
+ idempotency_key: client.getRetryPolicy()?.idempotencyKey?.(payload) ?? generateIdempotencyKey(),
16
+ };
17
+ }
18
+
19
+ /**
20
+ * Give a data-store import its own `import_id` under the same opt-in as {@link withIdempotencyKey}. The server
21
+ * takes the ID as the import job's ObjectId and refuses an unknown one older than 24 hours, so it is a fresh
22
+ * ObjectId: the current time in seconds, then random bytes.
23
+ */
24
+ export function withImportId<T extends { import_id?: string }>(client: ClientBase, payload: T): T {
25
+ if (payload.import_id || !client.getRetryPolicy()?.idempotencyKeys) {
26
+ return payload;
27
+ }
28
+ const durableId = client.getRetryPolicy()?.importId?.(payload);
29
+ if (durableId) return { ...payload, import_id: durableId };
30
+ const seconds = Math.floor(Date.now() / 1000)
31
+ .toString(16)
32
+ .padStart(8, '0');
33
+ return { ...payload, import_id: seconds + generateIdempotencyKey().replaceAll('-', '').slice(0, 16) };
34
+ }
@@ -1,3 +1,4 @@
1
+ import * as fs from 'node:fs';
1
2
  import type { Readable } from 'node:stream';
2
3
  import { finished } from 'node:stream/promises';
3
4
  import { StreamSource } from '../StreamSource.js';
@@ -6,13 +7,47 @@ import { StreamSource } from '../StreamSource.js';
6
7
  * A stream source that wraps a Node.js Readable stream.
7
8
  * This class is only works in Node.js environments.
8
9
  * Cancelling the web stream destroys the Node.js stream, releasing its underlying resource (e.g. a file descriptor).
10
+ *
11
+ * When the stream reads a whole local file (`fs.createReadStream(path)`), uploads send a file-backed `Blob`
12
+ * instead of the stream (see {@link replayableBody}): it can be retried without holding the file in memory.
9
13
  */
10
14
  export class NodeStreamSource extends StreamSource {
11
- constructor(stream: Readable, name: string, type?: string, id?: string) {
12
- super(readableToWebStream(stream) as ReadableStream, name, type, id);
15
+ private readonly filePath: string | undefined;
16
+
17
+ constructor(stream: Readable, name: string, type?: string, id?: string, size?: number) {
18
+ // read before wrapping: the web stream may start reading the Node.js stream
19
+ const filePath = wholeFilePath(stream);
20
+ super(readableToWebStream(stream) as ReadableStream, name, type, id, size);
21
+ this.filePath = filePath;
22
+ }
23
+
24
+ /**
25
+ * A `Blob` backed by the file the stream reads, from Node's `fs.openAsBlob`. Reading it reads the file from
26
+ * disk on demand, so each upload attempt streams the file again instead of buffering it.
27
+ */
28
+ override async replayableBody(): Promise<Blob | undefined> {
29
+ if (!this.filePath || typeof fs.openAsBlob !== 'function') return undefined;
30
+ return (await fs.openAsBlob(this.filePath, { type: this.type })) as Blob;
13
31
  }
14
32
  }
15
33
 
34
+ /**
35
+ * The path of the file a stream reads, when it reads all of it from the start: an `fs.ReadStream` opened by
36
+ * path with no range or encoding that nothing has read yet. Any other stream (a range, a descriptor, one that
37
+ * decodes the file to text, a stream already consumed, or one that is not a file) has no path, and is uploaded as
38
+ * a stream.
39
+ */
40
+ function wholeFilePath(stream: Readable): string | undefined {
41
+ if (!(stream instanceof fs.ReadStream)) return undefined;
42
+ const { path, start, end } = stream as fs.ReadStream & { start?: number; end?: number };
43
+ if (typeof path !== 'string') return undefined;
44
+ if ((start ?? 0) !== 0 || end !== Infinity) return undefined;
45
+ // an encoding uploads the decoded text (e.g. base64), not the file's bytes
46
+ if (stream.readableEncoding) return undefined;
47
+ if (stream.bytesRead > 0 || stream.readableDidRead) return undefined;
48
+ return path;
49
+ }
50
+
16
51
  /**
17
52
  * Not ReadableStream.from: it cancels by calling return() on the Node.js async iterator, which is a no-op
18
53
  * when nothing was read yet, so the Node.js stream would stay open. Also covers Bun, which lacks ReadableStream.from.
@@ -57,6 +57,7 @@ import {
57
57
  } from '@vertesia/common';
58
58
  import type { VertesiaClient } from '../client.js';
59
59
  import { EventSourceProvider } from '../execute.js';
60
+ import { withIdempotencyKey } from '../idempotency-key.js';
60
61
  import { fetchSignedUrl } from './signed-url.js';
61
62
  import { shouldCloseAgentRunStream, shouldCloseCompactRunStream } from './stream-termination.js';
62
63
 
@@ -101,8 +102,10 @@ export class AgentsApi extends ApiTopic {
101
102
  // retry policy explicitly rather than relying on POST being absent from its method list.
102
103
  // Rate-limiter pacing retries are unaffected: those happen before the request reaches the
103
104
  // handler. Process starts take no key and keep the client's policy.
104
- const unkeyedAgentStart = 'interaction' in payload && !payload.idempotency_key;
105
- return this.post('/', { payload, retryPolicy: unkeyedAgentStart ? false : undefined });
105
+ // A client whose policy sends idempotency keys gives the run a generated key instead.
106
+ const keyedPayload = 'interaction' in payload ? withIdempotencyKey(this.client, payload) : payload;
107
+ const unkeyedAgentStart = 'interaction' in keyedPayload && !keyedPayload.idempotency_key;
108
+ return this.post('/', { payload: keyedPayload, retryPolicy: unkeyedAgentStart ? false : undefined });
106
109
  }
107
110
 
108
111
  /**
@@ -0,0 +1,135 @@
1
+ import { ApiTopic, type ClientBase } from '@vertesia/api-fetch-client';
2
+ import type {
3
+ ContentSourceFoldersDiscovery,
4
+ ContentSourceReport,
5
+ ContentSourceReportQuery,
6
+ ContentSourceRootsDiscovery,
7
+ ContentSourceSampleDiscovery,
8
+ ContentSourceSchemaDiscovery,
9
+ ContentSourceSiteDiscovery,
10
+ ContentSourceStatus,
11
+ ContentSourceSummary,
12
+ CreateContentSourcePayload,
13
+ DeleteCountResult,
14
+ DiscoverContentSourceFoldersPayload,
15
+ DiscoverContentSourceSamplePayload,
16
+ DiscoverContentSourceSchemaPayload,
17
+ DiscoverContentSourceSitePayload,
18
+ ExternalContentSource,
19
+ InspectContentSourceFoldersPayload,
20
+ InspectContentSourceSamplePayload,
21
+ InspectContentSourceSchemaPayload,
22
+ SyncContentSourcePayload,
23
+ UpdateContentSourcePayload,
24
+ } from '@vertesia/common';
25
+
26
+ /**
27
+ * Folders of external content systems (SharePoint, Box) synced into the project without copies. Each source has
28
+ * a sync that imports the folder, then reads its changes on a schedule or on request.
29
+ */
30
+ export class ContentSourcesApi extends ApiTopic {
31
+ constructor(parent: ClientBase) {
32
+ super(parent, '/api/v1/content-sources');
33
+ }
34
+
35
+ list(): Promise<ExternalContentSource[]> {
36
+ return this.get('/');
37
+ }
38
+
39
+ /**
40
+ * Every source with what it syncs (site, library, folder) and how its sync stands: state, schedule, last
41
+ * successful round. Needs only content read access, and holds no connection or permission settings.
42
+ */
43
+ summary(): Promise<ContentSourceSummary[]> {
44
+ return this.get('/summary');
45
+ }
46
+
47
+ retrieve(id: string): Promise<ExternalContentSource> {
48
+ return this.get(`/${id}`);
49
+ }
50
+
51
+ /** Checks the folder with the system and registers the source. Nothing is imported until `sync` is called. */
52
+ create(payload: CreateContentSourcePayload): Promise<ExternalContentSource> {
53
+ return this.post('/', { payload });
54
+ }
55
+
56
+ /** Changes the name, description or sync settings, and, before the first sync, the root and folder. */
57
+ update(id: string, payload: UpdateContentSourcePayload): Promise<ExternalContentSource> {
58
+ return this.put(`/${id}`, { payload });
59
+ }
60
+
61
+ /** Stops the sync and removes the source. Synced documents are kept. */
62
+ delete(id: string): Promise<DeleteCountResult> {
63
+ return this.del(`/${id}`);
64
+ }
65
+
66
+ /** Syncs now: reads the changes, or, with `full`, lists the whole folder and removes deleted files. */
67
+ sync(id: string, payload: SyncContentSourcePayload = {}): Promise<ContentSourceStatus> {
68
+ return this.post(`/${id}/sync`, { payload });
69
+ }
70
+
71
+ /** The sync's state: the current and last rounds, and when the next one starts. */
72
+ status(id: string): Promise<ContentSourceStatus> {
73
+ return this.get(`/${id}/status`);
74
+ }
75
+
76
+ /**
77
+ * A page of what a sync round did with each file: created, updated, deleted, skipped or failed. Round IDs are in
78
+ * the status's `recent_rounds`. Pass the `next_cursor` of a page to read the next one.
79
+ */
80
+ report(id: string, roundId: string, query: ContentSourceReportQuery = {}): Promise<ContentSourceReport> {
81
+ return this.get(`/${id}/rounds/${encodeURIComponent(roundId)}/report`, { query: { ...query } });
82
+ }
83
+
84
+ /**
85
+ * Resolves a site through an OAuth provider and lists its document libraries. Works before a source exists,
86
+ * so it also tells whether the connection is set up correctly.
87
+ */
88
+ discoverSite(payload: DiscoverContentSourceSitePayload): Promise<ContentSourceSiteDiscovery> {
89
+ return this.post('/discover/site', { payload });
90
+ }
91
+
92
+ /** The direct subfolders of a folder of a document library, to browse to the folder to sync. */
93
+ discoverFolders(payload: DiscoverContentSourceFoldersPayload): Promise<ContentSourceFoldersDiscovery> {
94
+ return this.post('/discover/folders', { payload });
95
+ }
96
+
97
+ /** The content types of a document library with their columns, and the library's own columns. */
98
+ discoverSchema(payload: DiscoverContentSourceSchemaPayload): Promise<ContentSourceSchemaDiscovery> {
99
+ return this.post('/discover/schema', { payload });
100
+ }
101
+
102
+ /**
103
+ * A bounded sample of the files under a folder, with each file's content type and column values. The sample is
104
+ * spread over subfolders; `truncated` says whether the folder holds more than was read.
105
+ */
106
+ discoverSample(payload: DiscoverContentSourceSamplePayload): Promise<ContentSourceSampleDiscovery> {
107
+ return this.post('/discover/sample', { payload });
108
+ }
109
+
110
+ /**
111
+ * What a source's connection reaches: the document libraries of its SharePoint site, or the Box folders shared
112
+ * with its app. The caller names no OAuth provider or address: the source holds them.
113
+ */
114
+ inspectRoots(id: string): Promise<ContentSourceRootsDiscovery> {
115
+ return this.post(`/${id}/discover/roots`);
116
+ }
117
+
118
+ /** The direct subfolders of a folder the source reaches, at the top of its root by default. */
119
+ inspectFolders(
120
+ id: string,
121
+ payload: InspectContentSourceFoldersPayload = {},
122
+ ): Promise<ContentSourceFoldersDiscovery> {
123
+ return this.post(`/${id}/discover/folders`, { payload });
124
+ }
125
+
126
+ /** The content types (SharePoint) or metadata templates (Box) and their columns. */
127
+ inspectSchema(id: string, payload: InspectContentSourceSchemaPayload = {}): Promise<ContentSourceSchemaDiscovery> {
128
+ return this.post(`/${id}/discover/schema`, { payload });
129
+ }
130
+
131
+ /** A bounded sample of the files under a folder the source reaches, its own folder by default. */
132
+ inspectSample(id: string, payload: InspectContentSourceSamplePayload = {}): Promise<ContentSourceSampleDiscovery> {
133
+ return this.post(`/${id}/discover/sample`, { payload });
134
+ }
135
+ }
@@ -6,7 +6,11 @@ import type {
6
6
  CostModelPricesQuery,
7
7
  CostRunPriceQuery,
8
8
  CostRunPriceResponse,
9
+ InferenceBudgetSettings,
10
+ IntakeCostSummaryQuery,
11
+ IntakeCostSummaryResponse,
9
12
  ModelPriceComparisonResponse,
13
+ UpdateInferenceBudget,
10
14
  } from '@vertesia/common';
11
15
 
12
16
  export class CostApi extends ApiTopic {
@@ -14,6 +18,18 @@ export class CostApi extends ApiTopic {
14
18
  super(parent, '/api/v1/cost');
15
19
  }
16
20
 
21
+ getInferenceBudget(): Promise<InferenceBudgetSettings> {
22
+ return this.get('/budget');
23
+ }
24
+
25
+ updateInferenceBudget(payload: UpdateInferenceBudget): Promise<InferenceBudgetSettings> {
26
+ return this.put('/budget', { payload });
27
+ }
28
+
29
+ disableInferenceBudget(): Promise<InferenceBudgetSettings> {
30
+ return this.del('/budget');
31
+ }
32
+
17
33
  /**
18
34
  * Get cost analytics for the current project.
19
35
  * Returns cost breakdown by model/environment with pricing from billing export.
@@ -30,6 +46,14 @@ export class CostApi extends ApiTopic {
30
46
  return this.get('/model-prices', { query: { ...query } });
31
47
  }
32
48
 
49
+ /**
50
+ * The LLM and embedding cost of the current project's intake runs over a window: totals, a time series, and
51
+ * breakdowns by content type, outcome and document. Requires a billing read permission.
52
+ */
53
+ getIntakeCostSummary(query: IntakeCostSummaryQuery = {}): Promise<IntakeCostSummaryResponse> {
54
+ return this.get('/intake', { query: { ...query } });
55
+ }
56
+
33
57
  /**
34
58
  * Price a single interaction run or agent run.
35
59
  */
@@ -6,12 +6,16 @@ import {
6
6
  type DashboardArchiveResult,
7
7
  type DashboardBulkArchiveResult,
8
8
  type DashboardBulkDeleteResult,
9
+ type DashboardExport,
10
+ DashboardExportStatus,
9
11
  type DashboardItem,
10
12
  type DashboardStatus,
11
13
  type DashboardVersion,
12
14
  type DashboardVersionItem,
13
15
  type DashboardVersioningStatusResponse,
14
16
  DataStoreApiHeaders,
17
+ type ExportDashboardPayload,
18
+ type ExportDashboardPreviewPayload,
15
19
  type PromoteDashboardVersionPayload,
16
20
  type UpdateDashboardPayload,
17
21
  } from '@vertesia/common';
@@ -23,7 +27,9 @@ import {
23
27
  * - Multi-panel Vega/Vega-Lite visualizations
24
28
  * - SQL-backed data sources via named queries
25
29
  *
26
- * Note: Rendering is handled by the tools (data_preview_dashboard, data_render_dashboard).
30
+ * - PNG export of a saved dashboard ({@link DashboardApi.export}) or of an unsaved one
31
+ * ({@link DashboardApi.exportPreview}). Exports run in the background: poll them with
32
+ * {@link DashboardApi.getExport}, or wait for them with {@link DashboardApi.waitForExport}.
27
33
  */
28
34
  export class DashboardApi extends ApiTopic {
29
35
  private readonly storeId: string;
@@ -58,30 +64,24 @@ export class DashboardApi extends ApiTopic {
58
64
  /**
59
65
  * Create a new dashboard.
60
66
  *
61
- * @param payload - Dashboard configuration with queries and panels
67
+ * @param payload - Dashboard name, SQL data source and Vega-Lite spec
62
68
  * @returns The created dashboard
63
69
  *
64
70
  * @example
65
71
  * ```typescript
66
72
  * const dashboard = await client.data.dashboards(storeId).create({
67
73
  * name: 'Sales Overview',
68
- * queries: [
69
- * { name: 'revenue', sql: 'SELECT month, SUM(amount) FROM sales GROUP BY month' }
70
- * ],
71
- * panels: [
72
- * {
73
- * title: 'Monthly Revenue',
74
- * dataSources: ['revenue'],
75
- * position: { row: 0, col: 0 },
76
- * spec: {
77
- * mark: 'bar',
78
- * encoding: {
79
- * x: { field: 'month', type: 'ordinal' },
80
- * y: { field: 'sum_amount', type: 'quantitative' }
81
- * }
82
- * }
74
+ * dataSource: {
75
+ * kind: 'data_sql',
76
+ * query: 'SELECT month, SUM(amount) AS revenue FROM sales GROUP BY month',
77
+ * },
78
+ * spec: {
79
+ * mark: 'bar',
80
+ * encoding: {
81
+ * x: { field: 'month', type: 'ordinal' },
82
+ * y: { field: 'revenue', type: 'quantitative' }
83
83
  * }
84
- * ]
84
+ * }
85
85
  * });
86
86
  * ```
87
87
  */
@@ -110,6 +110,67 @@ export class DashboardApi extends ApiTopic {
110
110
  return this.put(`/${id}`, { payload, headers: this.storeHeaders() });
111
111
  }
112
112
 
113
+ /**
114
+ * Start rendering a saved dashboard as an image.
115
+ *
116
+ * Every call renders a new image from the current data. The export starts `running`: poll it
117
+ * with {@link getExport} or wait for it with {@link waitForExport}.
118
+ *
119
+ * @param id - Dashboard ID
120
+ * @param payload - Parameter values and render options
121
+ * @returns The started export
122
+ */
123
+ export(id: string, payload: ExportDashboardPayload = {}): Promise<DashboardExport> {
124
+ return this.post(`/${id}/export`, { payload, headers: this.storeHeaders() });
125
+ }
126
+
127
+ /**
128
+ * Start rendering an unsaved dashboard (SQL query and Vega-Lite spec) as an image, without saving it.
129
+ *
130
+ * Use it to check a spec before creating or updating a dashboard: an invalid spec or query makes
131
+ * the export fail with the list of problems.
132
+ *
133
+ * @param payload - The query, spec and render options
134
+ * @returns The started export
135
+ */
136
+ exportPreview(payload: ExportDashboardPreviewPayload): Promise<DashboardExport> {
137
+ return this.post('/export', { payload, headers: this.storeHeaders() });
138
+ }
139
+
140
+ /**
141
+ * Get the status of an export. Once it is `completed`, each call returns a fresh download URL.
142
+ *
143
+ * @param exportId - The `export_id` returned when the export was started
144
+ * @returns The export
145
+ */
146
+ getExport(exportId: string): Promise<DashboardExport> {
147
+ return this.get(`/exports/${exportId}`, { headers: this.storeHeaders() });
148
+ }
149
+
150
+ /**
151
+ * Poll an export until it is `completed` or `failed`.
152
+ *
153
+ * @param exportId - The `export_id` returned when the export was started
154
+ * @param options - Poll interval (default: 1s) and timeout (default: 5 minutes)
155
+ * @returns The completed or failed export
156
+ * @throws Error when the export is still running after `timeoutMs`
157
+ */
158
+ async waitForExport(exportId: string, options: DashboardExportWaitOptions = {}): Promise<DashboardExport> {
159
+ const pollIntervalMs = options.pollIntervalMs ?? 1000;
160
+ const timeoutMs = options.timeoutMs ?? 5 * 60 * 1000;
161
+ const deadline = Date.now() + timeoutMs;
162
+ while (true) {
163
+ const current = await this.getExport(exportId);
164
+ if (current.status !== DashboardExportStatus.RUNNING) {
165
+ return current;
166
+ }
167
+ if (Date.now() >= deadline) {
168
+ throw new Error(`Dashboard export ${exportId} is still running after ${timeoutMs}ms`);
169
+ }
170
+ await sleep(pollIntervalMs);
171
+ }
172
+ }
173
+
113
174
  /**
114
175
  * Archive (soft delete) a dashboard.
115
176
  *
@@ -215,3 +276,17 @@ export class DashboardApi extends ApiTopic {
215
276
  return this.put(`/${dashboardId}/versioning`, { payload: { enabled }, headers: this.storeHeaders() });
216
277
  }
217
278
  }
279
+
280
+ /**
281
+ * Options for {@link DashboardApi.waitForExport}.
282
+ */
283
+ export interface DashboardExportWaitOptions {
284
+ /** Delay between status checks, in milliseconds (default: 1000) */
285
+ pollIntervalMs?: number;
286
+ /** How long to wait before giving up, in milliseconds (default: 5 minutes) */
287
+ timeoutMs?: number;
288
+ }
289
+
290
+ function sleep(ms: number): Promise<void> {
291
+ return new Promise((resolve) => setTimeout(resolve, ms));
292
+ }