@kontext-dev/js-sdk 0.1.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.
Files changed (84) hide show
  1. package/README.md +70 -0
  2. package/dist/adapters/ai/index.cjs +175 -0
  3. package/dist/adapters/ai/index.cjs.map +1 -0
  4. package/dist/adapters/ai/index.d.cts +51 -0
  5. package/dist/adapters/ai/index.d.ts +51 -0
  6. package/dist/adapters/ai/index.js +173 -0
  7. package/dist/adapters/ai/index.js.map +1 -0
  8. package/dist/adapters/cloudflare/index.cjs +598 -0
  9. package/dist/adapters/cloudflare/index.cjs.map +1 -0
  10. package/dist/adapters/cloudflare/index.d.cts +214 -0
  11. package/dist/adapters/cloudflare/index.d.ts +214 -0
  12. package/dist/adapters/cloudflare/index.js +594 -0
  13. package/dist/adapters/cloudflare/index.js.map +1 -0
  14. package/dist/adapters/cloudflare/react.cjs +156 -0
  15. package/dist/adapters/cloudflare/react.cjs.map +1 -0
  16. package/dist/adapters/cloudflare/react.d.cts +68 -0
  17. package/dist/adapters/cloudflare/react.d.ts +68 -0
  18. package/dist/adapters/cloudflare/react.js +152 -0
  19. package/dist/adapters/cloudflare/react.js.map +1 -0
  20. package/dist/adapters/react/index.cjs +146 -0
  21. package/dist/adapters/react/index.cjs.map +1 -0
  22. package/dist/adapters/react/index.d.cts +103 -0
  23. package/dist/adapters/react/index.d.ts +103 -0
  24. package/dist/adapters/react/index.js +142 -0
  25. package/dist/adapters/react/index.js.map +1 -0
  26. package/dist/client/index.cjs +2415 -0
  27. package/dist/client/index.cjs.map +1 -0
  28. package/dist/client/index.d.cts +125 -0
  29. package/dist/client/index.d.ts +125 -0
  30. package/dist/client/index.js +2412 -0
  31. package/dist/client/index.js.map +1 -0
  32. package/dist/errors.cjs +213 -0
  33. package/dist/errors.cjs.map +1 -0
  34. package/dist/errors.d.cts +161 -0
  35. package/dist/errors.d.ts +161 -0
  36. package/dist/errors.js +201 -0
  37. package/dist/errors.js.map +1 -0
  38. package/dist/index-D5hS5PGn.d.ts +54 -0
  39. package/dist/index-DcL4a5Vq.d.cts +54 -0
  40. package/dist/index.cjs +4046 -0
  41. package/dist/index.cjs.map +1 -0
  42. package/dist/index.d.cts +15 -0
  43. package/dist/index.d.ts +15 -0
  44. package/dist/index.js +4029 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/kontext-CgIBANFo.d.cts +308 -0
  47. package/dist/kontext-CgIBANFo.d.ts +308 -0
  48. package/dist/management/index.cjs +867 -0
  49. package/dist/management/index.cjs.map +1 -0
  50. package/dist/management/index.d.cts +467 -0
  51. package/dist/management/index.d.ts +467 -0
  52. package/dist/management/index.js +855 -0
  53. package/dist/management/index.js.map +1 -0
  54. package/dist/mcp/index.cjs +799 -0
  55. package/dist/mcp/index.cjs.map +1 -0
  56. package/dist/mcp/index.d.cts +231 -0
  57. package/dist/mcp/index.d.ts +231 -0
  58. package/dist/mcp/index.js +797 -0
  59. package/dist/mcp/index.js.map +1 -0
  60. package/dist/oauth/index.cjs +418 -0
  61. package/dist/oauth/index.cjs.map +1 -0
  62. package/dist/oauth/index.d.cts +235 -0
  63. package/dist/oauth/index.d.ts +235 -0
  64. package/dist/oauth/index.js +414 -0
  65. package/dist/oauth/index.js.map +1 -0
  66. package/dist/server/index.cjs +1634 -0
  67. package/dist/server/index.cjs.map +1 -0
  68. package/dist/server/index.d.cts +10 -0
  69. package/dist/server/index.d.ts +10 -0
  70. package/dist/server/index.js +1629 -0
  71. package/dist/server/index.js.map +1 -0
  72. package/dist/types-CzhnlJHW.d.cts +397 -0
  73. package/dist/types-CzhnlJHW.d.ts +397 -0
  74. package/dist/types-RIzHnRpk.d.cts +23 -0
  75. package/dist/types-RIzHnRpk.d.ts +23 -0
  76. package/dist/verifier-CoJmYiw3.d.cts +109 -0
  77. package/dist/verifier-CoJmYiw3.d.ts +109 -0
  78. package/dist/verify/index.cjs +319 -0
  79. package/dist/verify/index.cjs.map +1 -0
  80. package/dist/verify/index.d.cts +63 -0
  81. package/dist/verify/index.d.ts +63 -0
  82. package/dist/verify/index.js +315 -0
  83. package/dist/verify/index.js.map +1 -0
  84. package/package.json +221 -0
@@ -0,0 +1,855 @@
1
+ // src/errors.ts
2
+ var KontextError = class extends Error {
3
+ /** Brand field for type narrowing without instanceof */
4
+ kontextError = true;
5
+ /** Machine-readable error code, always prefixed with `kontext_` */
6
+ code;
7
+ /** HTTP status code when applicable */
8
+ statusCode;
9
+ /** Auto-generated link to error documentation */
10
+ docsUrl;
11
+ /** Server request ID for debugging / support escalation */
12
+ requestId;
13
+ /** Contextual metadata bag (integration IDs, param names, etc.) */
14
+ meta;
15
+ constructor(message, code, options) {
16
+ super(message, { cause: options?.cause });
17
+ this.name = "KontextError";
18
+ this.code = code;
19
+ this.statusCode = options?.statusCode;
20
+ this.requestId = options?.requestId;
21
+ this.meta = options?.meta ?? {};
22
+ this.docsUrl = `https://docs.kontext.dev/errors/${code}`;
23
+ Object.setPrototypeOf(this, new.target.prototype);
24
+ }
25
+ toJSON() {
26
+ return {
27
+ name: this.name,
28
+ code: this.code,
29
+ message: this.message,
30
+ statusCode: this.statusCode,
31
+ docsUrl: this.docsUrl,
32
+ requestId: this.requestId,
33
+ meta: Object.keys(this.meta).length > 0 ? this.meta : void 0
34
+ };
35
+ }
36
+ toString() {
37
+ const parts = [`[${this.code}] ${this.message}`];
38
+ if (this.docsUrl) parts.push(`Docs: ${this.docsUrl}`);
39
+ if (this.requestId) parts.push(`Request ID: ${this.requestId}`);
40
+ return parts.join("\n");
41
+ }
42
+ };
43
+ var AuthorizationRequiredError = class extends KontextError {
44
+ authorizationUrl;
45
+ constructor(message = "Authorization required. Complete the OAuth flow to continue.", options) {
46
+ super(message, "kontext_authorization_required", {
47
+ statusCode: 401,
48
+ ...options
49
+ });
50
+ this.name = "AuthorizationRequiredError";
51
+ this.authorizationUrl = options?.authorizationUrl;
52
+ }
53
+ };
54
+ var OAuthError = class extends KontextError {
55
+ errorCode;
56
+ errorDescription;
57
+ constructor(message, code, options) {
58
+ super(message, code, {
59
+ statusCode: options?.statusCode ?? 400,
60
+ ...options
61
+ });
62
+ this.name = "OAuthError";
63
+ this.errorCode = options?.errorCode;
64
+ this.errorDescription = options?.errorDescription;
65
+ }
66
+ };
67
+ var IntegrationConnectionRequiredError = class extends KontextError {
68
+ integrationId;
69
+ integrationName;
70
+ connectUrl;
71
+ constructor(integrationId, options) {
72
+ super(
73
+ options?.message ?? `Connection to integration "${integrationId}" is required. Visit the connect URL to authorize.`,
74
+ "kontext_integration_connection_required",
75
+ { statusCode: 403, ...options }
76
+ );
77
+ this.name = "IntegrationConnectionRequiredError";
78
+ this.integrationId = integrationId;
79
+ this.integrationName = options?.integrationName;
80
+ this.connectUrl = options?.connectUrl;
81
+ }
82
+ };
83
+ var NetworkError = class extends KontextError {
84
+ constructor(message = "Network error. Check your internet connection and that the server is reachable.", options) {
85
+ super(message, "kontext_network_error", options);
86
+ this.name = "NetworkError";
87
+ }
88
+ };
89
+ var HttpError = class extends KontextError {
90
+ retryAfter;
91
+ validationErrors;
92
+ constructor(message, code, options) {
93
+ super(message, code, {
94
+ statusCode: options?.statusCode,
95
+ ...options
96
+ });
97
+ this.name = "HttpError";
98
+ this.retryAfter = options?.retryAfter;
99
+ this.validationErrors = options?.validationErrors;
100
+ }
101
+ };
102
+ function parseHttpError(statusCode, body) {
103
+ const message = typeof body === "object" && body !== null && "message" in body ? String(body.message) : `HTTP ${statusCode}`;
104
+ const errorCode = typeof body === "object" && body !== null && "code" in body ? String(body.code) : void 0;
105
+ switch (statusCode) {
106
+ case 400:
107
+ if (typeof body === "object" && body !== null && "errors" in body && Array.isArray(body.errors)) {
108
+ return new HttpError(message, "kontext_validation_error", {
109
+ statusCode: 400,
110
+ validationErrors: body.errors
111
+ });
112
+ }
113
+ return new KontextError(message, errorCode ?? "kontext_bad_request", {
114
+ statusCode: 400
115
+ });
116
+ case 401:
117
+ return new AuthorizationRequiredError(message);
118
+ case 403:
119
+ if (errorCode === "INTEGRATION_CONNECTION_REQUIRED") {
120
+ const details = body;
121
+ return new IntegrationConnectionRequiredError(
122
+ details.integrationId ?? "unknown",
123
+ {
124
+ integrationName: details.integrationName,
125
+ connectUrl: details.connectUrl,
126
+ message
127
+ }
128
+ );
129
+ }
130
+ return new HttpError(message, "kontext_policy_denied", {
131
+ statusCode: 403,
132
+ meta: { policy: body?.policy }
133
+ });
134
+ case 404:
135
+ return new HttpError(message, "kontext_not_found", { statusCode: 404 });
136
+ case 429: {
137
+ const retryAfter = typeof body === "object" && body !== null && "retryAfter" in body ? Number(body.retryAfter) : void 0;
138
+ return new HttpError(
139
+ retryAfter ? `Rate limit exceeded. Retry after ${retryAfter} seconds.` : "Rate limit exceeded. Wait and retry.",
140
+ "kontext_rate_limited",
141
+ { statusCode: 429, retryAfter }
142
+ );
143
+ }
144
+ default:
145
+ if (statusCode >= 500) {
146
+ return new HttpError(
147
+ `Server error (HTTP ${statusCode}): ${message}`,
148
+ "kontext_server_error",
149
+ { statusCode }
150
+ );
151
+ }
152
+ return new KontextError(message, errorCode ?? "kontext_unknown_error", {
153
+ statusCode
154
+ });
155
+ }
156
+ }
157
+
158
+ // src/management/auth.ts
159
+ async function authenticateServiceAccount(tokenUrl, credentials, scopes, audience) {
160
+ const params = new URLSearchParams({
161
+ grant_type: "client_credentials"
162
+ });
163
+ if (scopes && scopes.length > 0) {
164
+ params.set("scope", scopes.join(" "));
165
+ }
166
+ if (audience) {
167
+ params.set("audience", audience);
168
+ }
169
+ const basicAuth = Buffer.from(
170
+ `${credentials.clientId}:${credentials.clientSecret}`
171
+ ).toString("base64");
172
+ let response;
173
+ try {
174
+ response = await fetch(tokenUrl, {
175
+ method: "POST",
176
+ headers: {
177
+ "Content-Type": "application/x-www-form-urlencoded",
178
+ Accept: "application/json",
179
+ Authorization: `Basic ${basicAuth}`
180
+ },
181
+ body: params.toString()
182
+ });
183
+ } catch (err) {
184
+ throw new NetworkError("Failed to connect to token endpoint", {
185
+ cause: err instanceof Error ? err : void 0
186
+ });
187
+ }
188
+ if (!response.ok) {
189
+ let errorBody;
190
+ try {
191
+ errorBody = await response.json();
192
+ } catch {
193
+ errorBody = await response.text();
194
+ }
195
+ if (response.status === 401) {
196
+ throw new AuthorizationRequiredError(
197
+ "Invalid service account credentials"
198
+ );
199
+ }
200
+ const errorCode = typeof errorBody === "object" && errorBody !== null && "error" in errorBody ? String(errorBody.error) : "unknown_error";
201
+ const errorDescription = typeof errorBody === "object" && errorBody !== null && "error_description" in errorBody ? String(
202
+ errorBody.error_description
203
+ ) : void 0;
204
+ throw new OAuthError(
205
+ errorDescription ?? `Token request failed: ${errorCode}`,
206
+ "kontext_oauth_token_exchange_failed",
207
+ { errorCode, errorDescription }
208
+ );
209
+ }
210
+ const tokenData = await response.json();
211
+ return {
212
+ accessToken: tokenData.access_token,
213
+ tokenType: tokenData.token_type,
214
+ expiresAt: tokenData.expires_in ? new Date(Date.now() + tokenData.expires_in * 1e3) : null,
215
+ scope: tokenData.scope
216
+ };
217
+ }
218
+ var TokenManager = class {
219
+ // Refresh 60 seconds before expiry
220
+ constructor(tokenUrl, credentials, scopes, audience) {
221
+ this.tokenUrl = tokenUrl;
222
+ this.credentials = credentials;
223
+ this.scopes = scopes;
224
+ this.audience = audience;
225
+ }
226
+ token = null;
227
+ tokenPromise = null;
228
+ bufferSeconds = 60;
229
+ /**
230
+ * Get a valid access token, refreshing if necessary
231
+ */
232
+ async getAccessToken() {
233
+ if (this.token && !this.isExpired(this.token)) {
234
+ return this.token.accessToken;
235
+ }
236
+ if (!this.tokenPromise) {
237
+ this.tokenPromise = this.refresh().finally(() => {
238
+ this.tokenPromise = null;
239
+ });
240
+ }
241
+ const token = await this.tokenPromise;
242
+ return token.accessToken;
243
+ }
244
+ /**
245
+ * Force a token refresh
246
+ */
247
+ async refresh() {
248
+ this.token = await authenticateServiceAccount(
249
+ this.tokenUrl,
250
+ this.credentials,
251
+ this.scopes,
252
+ this.audience
253
+ );
254
+ return this.token;
255
+ }
256
+ /**
257
+ * Clear the cached token
258
+ */
259
+ clear() {
260
+ this.token = null;
261
+ this.tokenPromise = null;
262
+ }
263
+ isExpired(token) {
264
+ if (!token.expiresAt) {
265
+ return false;
266
+ }
267
+ const bufferMs = this.bufferSeconds * 1e3;
268
+ return Date.now() >= token.expiresAt.getTime() - bufferMs;
269
+ }
270
+ };
271
+
272
+ // src/management/http.ts
273
+ var HttpClient = class {
274
+ constructor(config) {
275
+ this.config = config;
276
+ this.baseUrl = `${config.baseUrl.replace(/\/$/, "")}/api/${config.apiVersion}`;
277
+ }
278
+ baseUrl;
279
+ /**
280
+ * Make a GET request
281
+ */
282
+ async get(path, params) {
283
+ const url = this.buildUrl(path, params);
284
+ return this.request("GET", url, void 0, true);
285
+ }
286
+ /**
287
+ * Make a POST request
288
+ */
289
+ async post(path, body) {
290
+ const url = this.buildUrl(path);
291
+ return this.request("POST", url, body, true);
292
+ }
293
+ /**
294
+ * Make a POST request without expecting a response body
295
+ */
296
+ async postNoContent(path, body) {
297
+ const url = this.buildUrl(path);
298
+ await this.request("POST", url, body, false);
299
+ }
300
+ /**
301
+ * Make a PUT request
302
+ */
303
+ async put(path, body) {
304
+ const url = this.buildUrl(path);
305
+ return this.request("PUT", url, body, true);
306
+ }
307
+ /**
308
+ * Make a PATCH request
309
+ */
310
+ async patch(path, body) {
311
+ const url = this.buildUrl(path);
312
+ return this.request("PATCH", url, body, true);
313
+ }
314
+ /**
315
+ * Make a DELETE request
316
+ */
317
+ async delete(path) {
318
+ const url = this.buildUrl(path);
319
+ await this.request("DELETE", url, void 0, false);
320
+ }
321
+ /**
322
+ * Make a DELETE request expecting a response body
323
+ */
324
+ async deleteJson(path) {
325
+ const url = this.buildUrl(path);
326
+ return this.request("DELETE", url, void 0, true);
327
+ }
328
+ buildUrl(path, params) {
329
+ const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
330
+ const url = new URL(normalizedPath, this.baseUrl + "/");
331
+ if (params) {
332
+ for (const [key, value] of Object.entries(params)) {
333
+ if (value !== void 0) {
334
+ url.searchParams.set(key, String(value));
335
+ }
336
+ }
337
+ }
338
+ return url.toString();
339
+ }
340
+ async request(method, url, body, expectBody) {
341
+ const accessToken = await this.config.tokenManager.getAccessToken();
342
+ const headers = {
343
+ Authorization: `Bearer ${accessToken}`,
344
+ Accept: "application/json"
345
+ };
346
+ if (body !== void 0) {
347
+ headers["Content-Type"] = "application/json";
348
+ }
349
+ let response;
350
+ try {
351
+ response = await fetch(url, {
352
+ method,
353
+ headers,
354
+ body: body !== void 0 ? JSON.stringify(body) : void 0
355
+ });
356
+ } catch (err) {
357
+ throw new NetworkError(`Request to ${url} failed`, {
358
+ cause: err instanceof Error ? err : void 0
359
+ });
360
+ }
361
+ if (response.status === 204) {
362
+ if (expectBody) {
363
+ throw new NetworkError(
364
+ `Expected response body but got 204 from ${url}`
365
+ );
366
+ }
367
+ return;
368
+ }
369
+ let responseBody;
370
+ if (expectBody || !response.ok) {
371
+ const contentType = response.headers.get("content-type");
372
+ if (contentType?.includes("application/json")) {
373
+ try {
374
+ responseBody = await response.json();
375
+ } catch {
376
+ responseBody = void 0;
377
+ }
378
+ } else {
379
+ responseBody = await response.text();
380
+ }
381
+ }
382
+ if (!response.ok) {
383
+ throw parseHttpError(response.status, responseBody);
384
+ }
385
+ if (!expectBody) {
386
+ return;
387
+ }
388
+ return responseBody;
389
+ }
390
+ };
391
+ function paginationToParams(pagination) {
392
+ return {
393
+ cursor: pagination?.cursor,
394
+ limit: pagination?.limit
395
+ };
396
+ }
397
+
398
+ // src/management/service-accounts.ts
399
+ var ServiceAccountsResource = class {
400
+ constructor(http) {
401
+ this.http = http;
402
+ }
403
+ /**
404
+ * Create a new service account
405
+ * @param input Service account creation parameters
406
+ * @returns The created service account with credentials
407
+ */
408
+ async create(input) {
409
+ return this.http.post(
410
+ "/service-accounts",
411
+ input
412
+ );
413
+ }
414
+ /**
415
+ * List all service accounts
416
+ * @param pagination Optional pagination parameters
417
+ * @returns List of service accounts
418
+ */
419
+ async list(pagination) {
420
+ return this.http.get(
421
+ "/service-accounts",
422
+ paginationToParams(pagination)
423
+ );
424
+ }
425
+ /**
426
+ * Get a service account by ID
427
+ * @param id Service account ID
428
+ * @returns The service account
429
+ */
430
+ async get(id) {
431
+ return this.http.get(`/service-accounts/${id}`);
432
+ }
433
+ /**
434
+ * Rotate a service account's client secret
435
+ * @param id Service account ID
436
+ * @returns New credentials
437
+ */
438
+ async rotateSecret(id) {
439
+ return this.http.post(
440
+ `/service-accounts/${id}/rotate-secret`
441
+ );
442
+ }
443
+ /**
444
+ * Revoke (delete) a service account
445
+ * @param id Service account ID
446
+ */
447
+ async revoke(id) {
448
+ await this.http.delete(`/service-accounts/${id}`);
449
+ }
450
+ };
451
+
452
+ // src/management/applications.ts
453
+ var ApplicationsResource = class {
454
+ constructor(http) {
455
+ this.http = http;
456
+ }
457
+ /**
458
+ * Create a new application
459
+ * @param input Application creation parameters
460
+ * @returns The created application with OAuth config
461
+ */
462
+ async create(input) {
463
+ return this.http.post("/applications", input);
464
+ }
465
+ /**
466
+ * List all applications
467
+ * @param pagination Optional pagination parameters
468
+ * @returns List of applications
469
+ */
470
+ async list(pagination) {
471
+ return this.http.get(
472
+ "/applications",
473
+ paginationToParams(pagination)
474
+ );
475
+ }
476
+ /**
477
+ * Get an application by ID
478
+ * @param id Application ID
479
+ * @returns The application
480
+ */
481
+ async get(id) {
482
+ return this.http.get(`/applications/${id}`);
483
+ }
484
+ /**
485
+ * Update an application
486
+ * @param id Application ID
487
+ * @param input Update parameters
488
+ * @returns The updated application
489
+ */
490
+ async update(id, input) {
491
+ return this.http.patch(`/applications/${id}`, input);
492
+ }
493
+ /**
494
+ * Archive an application (soft delete)
495
+ * @param id Application ID
496
+ */
497
+ async archive(id) {
498
+ await this.http.delete(`/applications/${id}`);
499
+ }
500
+ /**
501
+ * Get an application's OAuth configuration
502
+ * @param id Application ID
503
+ * @returns The OAuth configuration
504
+ */
505
+ async getOAuth(id) {
506
+ return this.http.get(`/applications/${id}/oauth`);
507
+ }
508
+ /**
509
+ * Update an application's OAuth configuration
510
+ * @param id Application ID
511
+ * @param input OAuth update parameters
512
+ * @returns The updated OAuth configuration
513
+ */
514
+ async updateOAuth(id, input) {
515
+ return this.http.patch(
516
+ `/applications/${id}/oauth`,
517
+ input
518
+ );
519
+ }
520
+ /**
521
+ * Rotate an application's client secret (confidential clients only)
522
+ * @param id Application ID
523
+ * @returns The new OAuth configuration with new secret
524
+ */
525
+ async rotateSecret(id) {
526
+ return this.http.post(
527
+ `/applications/${id}/rotate-secret`
528
+ );
529
+ }
530
+ /**
531
+ * List integrations attached to an application
532
+ * @param id Application ID
533
+ * @returns List of integration IDs
534
+ */
535
+ async listIntegrations(id) {
536
+ return this.http.get(
537
+ `/applications/${id}/integrations`
538
+ );
539
+ }
540
+ /**
541
+ * Set the integrations attached to an application (replaces all)
542
+ * @param id Application ID
543
+ * @param input Integration IDs to attach
544
+ * @returns Updated list of integration IDs
545
+ */
546
+ async setIntegrations(id, input) {
547
+ return this.http.put(
548
+ `/applications/${id}/integrations`,
549
+ input
550
+ );
551
+ }
552
+ /**
553
+ * Attach a single integration to an application
554
+ * @param id Application ID
555
+ * @param integrationId Integration ID to attach
556
+ */
557
+ async attachIntegration(id, integrationId) {
558
+ await this.http.postNoContent(
559
+ `/applications/${id}/integrations/${integrationId}`
560
+ );
561
+ }
562
+ /**
563
+ * Detach a single integration from an application
564
+ * @param id Application ID
565
+ * @param integrationId Integration ID to detach
566
+ */
567
+ async detachIntegration(id, integrationId) {
568
+ await this.http.delete(`/applications/${id}/integrations/${integrationId}`);
569
+ }
570
+ /**
571
+ * Revoke all agent sessions for an application
572
+ * @param id Application ID
573
+ */
574
+ async revokeAllAgentSessions(id) {
575
+ return this.http.deleteJson(
576
+ `/applications/${id}/sessions`
577
+ );
578
+ }
579
+ };
580
+
581
+ // src/management/integrations.ts
582
+ var IntegrationsResource = class {
583
+ constructor(http) {
584
+ this.http = http;
585
+ }
586
+ /**
587
+ * Create a new integration
588
+ * @param input Integration creation parameters
589
+ * @returns The created integration
590
+ */
591
+ async create(input) {
592
+ return this.http.post("/integrations", input);
593
+ }
594
+ /**
595
+ * List all integrations
596
+ * @param pagination Optional pagination parameters
597
+ * @returns List of integrations
598
+ */
599
+ async list(pagination) {
600
+ return this.http.get(
601
+ "/integrations",
602
+ paginationToParams(pagination)
603
+ );
604
+ }
605
+ /**
606
+ * Get an integration by ID
607
+ * @param id Integration ID
608
+ * @returns The integration
609
+ */
610
+ async get(id) {
611
+ return this.http.get(`/integrations/${id}`);
612
+ }
613
+ /**
614
+ * Update an integration
615
+ * @param id Integration ID
616
+ * @param input Update parameters
617
+ * @returns The updated integration
618
+ */
619
+ async update(id, input) {
620
+ return this.http.patch(`/integrations/${id}`, input);
621
+ }
622
+ /**
623
+ * Archive an integration (soft delete)
624
+ * @param id Integration ID
625
+ */
626
+ async archive(id) {
627
+ await this.http.delete(`/integrations/${id}`);
628
+ }
629
+ /**
630
+ * Validate an integration (test connectivity)
631
+ * @param id Integration ID
632
+ * @returns Validation result
633
+ */
634
+ async validate(id) {
635
+ return this.http.post(
636
+ `/integrations/${id}/validate`
637
+ );
638
+ }
639
+ };
640
+
641
+ // src/management/agent-sessions.ts
642
+ var AgentSessionsResource = class {
643
+ constructor(http) {
644
+ this.http = http;
645
+ }
646
+ /**
647
+ * List all agent sessions
648
+ * @param params Optional filter and pagination parameters
649
+ * @returns List of agent sessions
650
+ */
651
+ async list(applicationId, params) {
652
+ return this.http.get(
653
+ `/applications/${applicationId}/sessions`,
654
+ {
655
+ status: params?.status,
656
+ includeInactive: params?.includeInactive ? "true" : void 0,
657
+ limit: params?.limit
658
+ }
659
+ );
660
+ }
661
+ /**
662
+ * Get an agent session by ID
663
+ * @param id Agent session ID
664
+ * @returns The agent session
665
+ */
666
+ async get(applicationId, sessionId) {
667
+ return this.http.get(
668
+ `/applications/${applicationId}/sessions/${sessionId}`
669
+ );
670
+ }
671
+ /**
672
+ * Revoke all sessions for an application
673
+ */
674
+ async revokeAll(applicationId) {
675
+ return this.http.deleteJson(
676
+ `/applications/${applicationId}/sessions`
677
+ );
678
+ }
679
+ };
680
+
681
+ // src/management/traces.ts
682
+ var TracesResource = class {
683
+ constructor(http) {
684
+ this.http = http;
685
+ }
686
+ /**
687
+ * List traces
688
+ * @param params Optional filter and pagination parameters
689
+ * @returns List of traces
690
+ */
691
+ async list(params) {
692
+ const agentId = params?.agentId ?? params?.applicationId;
693
+ const offsetFromCursor = params?.cursor && !Number.isNaN(Number(params.cursor)) ? Number(params.cursor) : void 0;
694
+ return this.http.get("/traces", {
695
+ limit: params?.limit,
696
+ offset: params?.offset ?? offsetFromCursor,
697
+ userId: params?.userId,
698
+ sessionId: params?.sessionId,
699
+ agentId
700
+ });
701
+ }
702
+ /**
703
+ * Get a trace by ID with its events
704
+ * @param id Trace ID
705
+ * @returns The trace with events
706
+ */
707
+ async get(id, params) {
708
+ const response = await this.http.get(`/traces/${id}`, {
709
+ userId: params?.userId
710
+ });
711
+ if ("trace" in response && response.trace) {
712
+ return response;
713
+ }
714
+ const events = response.events ?? [];
715
+ const first = events[0];
716
+ const last = events.length > 0 ? events[events.length - 1] : void 0;
717
+ const traceId = first?.traceId ?? id;
718
+ const sessionId = first?.sessionId ?? "";
719
+ const okCount = events.filter((event) => event.status === "ok").length;
720
+ const warnCount = events.filter((event) => event.status === "warn").length;
721
+ const errorCount = events.filter(
722
+ (event) => ["error_remote", "error_proxy", "error_auth", "error"].includes(
723
+ event.status
724
+ )
725
+ ).length;
726
+ return {
727
+ trace: {
728
+ traceId,
729
+ sessionId,
730
+ startedAt: first?.createdAt ?? null,
731
+ endedAt: last?.createdAt ?? null,
732
+ eventCount: events.length,
733
+ okCount,
734
+ warnCount,
735
+ errorCount,
736
+ agentId: first?.agentId,
737
+ agentSessionId: first?.agentSessionId ?? void 0
738
+ },
739
+ events
740
+ };
741
+ }
742
+ /**
743
+ * Get trace statistics
744
+ * @param params Optional filter parameters
745
+ * @returns Trace statistics
746
+ */
747
+ async stats(params) {
748
+ const period = params?.period ?? (params?.startTime ? inferPeriodFromStartTime(params.startTime) : void 0);
749
+ const response = await this.http.get("/traces/stats", {
750
+ period,
751
+ userId: params?.userId
752
+ });
753
+ if ("stats" in response) {
754
+ return response;
755
+ }
756
+ return { stats: response };
757
+ }
758
+ };
759
+ var EventsResource = class {
760
+ constructor(http) {
761
+ this.http = http;
762
+ }
763
+ /**
764
+ * List events
765
+ * @param params Optional filter and pagination parameters
766
+ * @returns List of events
767
+ */
768
+ async list(params) {
769
+ return this.http.get("/mcp-events", {
770
+ limit: params?.limit
771
+ });
772
+ }
773
+ };
774
+ function inferPeriodFromStartTime(startTime) {
775
+ const startMs = Date.parse(startTime);
776
+ if (Number.isNaN(startMs)) {
777
+ return "7d";
778
+ }
779
+ const diffMs = Date.now() - startMs;
780
+ const diffDays = Math.ceil(diffMs / (24 * 60 * 60 * 1e3));
781
+ if (diffDays <= 1) return "1d";
782
+ if (diffDays <= 7) return "7d";
783
+ return "30d";
784
+ }
785
+
786
+ // src/management/client.ts
787
+ var DEFAULT_API_VERSION = "v1";
788
+ var KontextManagementClient = class {
789
+ tokenManager;
790
+ http;
791
+ /** Service Accounts resource */
792
+ serviceAccounts;
793
+ /** Applications resource */
794
+ applications;
795
+ /** Integrations resource */
796
+ integrations;
797
+ /** Agent Sessions resource (alias: agentInstances) */
798
+ agentSessions;
799
+ /** Agent Instances resource (alias for agentSessions, future naming) */
800
+ agentInstances;
801
+ /** Traces resource */
802
+ traces;
803
+ /** Events resource */
804
+ events;
805
+ constructor(config) {
806
+ const baseUrl = config.baseUrl.replace(/\/$/, "");
807
+ const apiVersion = config.apiVersion ?? DEFAULT_API_VERSION;
808
+ const tokenUrl = config.tokenUrl ?? `${baseUrl}/oauth2/token`;
809
+ const scopes = config.scopes ?? ["management:all"];
810
+ const audience = config.audience ?? `${baseUrl}/api/${apiVersion}`;
811
+ this.tokenManager = new TokenManager(
812
+ tokenUrl,
813
+ {
814
+ clientId: config.credentials.clientId,
815
+ clientSecret: config.credentials.clientSecret
816
+ },
817
+ scopes,
818
+ audience
819
+ );
820
+ this.http = new HttpClient({
821
+ baseUrl,
822
+ apiVersion,
823
+ tokenManager: this.tokenManager
824
+ });
825
+ this.serviceAccounts = new ServiceAccountsResource(this.http);
826
+ this.applications = new ApplicationsResource(this.http);
827
+ this.integrations = new IntegrationsResource(this.http);
828
+ this.agentSessions = new AgentSessionsResource(this.http);
829
+ this.agentInstances = this.agentSessions;
830
+ this.traces = new TracesResource(this.http);
831
+ this.events = new EventsResource(this.http);
832
+ }
833
+ /**
834
+ * Force refresh the access token
835
+ * Useful if you need to ensure a fresh token before a critical operation
836
+ */
837
+ async refreshToken() {
838
+ await this.tokenManager.refresh();
839
+ }
840
+ /**
841
+ * Clear the cached access token
842
+ * Useful when credentials have been rotated
843
+ */
844
+ clearToken() {
845
+ this.tokenManager.clear();
846
+ }
847
+ };
848
+
849
+ // src/management/types.ts
850
+ var TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange";
851
+ var TOKEN_TYPE_ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token";
852
+
853
+ export { AgentSessionsResource, ApplicationsResource, EventsResource, IntegrationsResource, KontextManagementClient, ServiceAccountsResource, TOKEN_EXCHANGE_GRANT_TYPE, TOKEN_TYPE_ACCESS_TOKEN, TokenManager, TracesResource, authenticateServiceAccount };
854
+ //# sourceMappingURL=index.js.map
855
+ //# sourceMappingURL=index.js.map