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