cngkit 1.1.2 → 1.1.4

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 (54) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +47 -10
  3. package/dist/chunk-HBBUFPJG.js +4585 -0
  4. package/dist/chunk-HBBUFPJG.js.map +1 -0
  5. package/dist/chunk-PZ5AY32C.js +10 -0
  6. package/dist/chunk-PZ5AY32C.js.map +1 -0
  7. package/dist/chunk-SNTLRTQ2.js +34 -0
  8. package/dist/chunk-SNTLRTQ2.js.map +1 -0
  9. package/dist/chunk-SSRUN6G5.js +524 -0
  10. package/dist/chunk-SSRUN6G5.js.map +1 -0
  11. package/dist/chunk-XWVFKUUD.js +22 -0
  12. package/dist/chunk-XWVFKUUD.js.map +1 -0
  13. package/dist/chunk-YY2VGJ5N.js +114 -0
  14. package/dist/chunk-YY2VGJ5N.js.map +1 -0
  15. package/dist/cli.js +88 -0
  16. package/dist/cli.js.map +1 -0
  17. package/dist/commands/_app.js +11 -0
  18. package/dist/commands/_app.js.map +1 -0
  19. package/dist/commands/coderoom/index.js +24 -0
  20. package/dist/commands/coderoom/index.js.map +1 -0
  21. package/dist/commands/coderoom/join.js +29 -0
  22. package/dist/commands/coderoom/join.js.map +1 -0
  23. package/dist/commands/coderoom/share.js +29 -0
  24. package/dist/commands/coderoom/share.js.map +1 -0
  25. package/dist/commands/index.js +19 -0
  26. package/dist/commands/index.js.map +1 -0
  27. package/dist/commands/knowledges/audiences.js +26 -0
  28. package/dist/commands/knowledges/audiences.js.map +1 -0
  29. package/dist/commands/knowledges/files.js +44 -0
  30. package/dist/commands/knowledges/files.js.map +1 -0
  31. package/dist/commands/knowledges/glob.js +38 -0
  32. package/dist/commands/knowledges/glob.js.map +1 -0
  33. package/dist/commands/knowledges/grep.js +61 -0
  34. package/dist/commands/knowledges/grep.js.map +1 -0
  35. package/dist/commands/knowledges/index.js +24 -0
  36. package/dist/commands/knowledges/index.js.map +1 -0
  37. package/dist/commands/knowledges/list.js +29 -0
  38. package/dist/commands/knowledges/list.js.map +1 -0
  39. package/dist/commands/knowledges/read.js +44 -0
  40. package/dist/commands/knowledges/read.js.map +1 -0
  41. package/dist/commands/knowledges/search.js +29 -0
  42. package/dist/commands/knowledges/search.js.map +1 -0
  43. package/dist/commands/knowledges/status.js +26 -0
  44. package/dist/commands/knowledges/status.js.map +1 -0
  45. package/dist/commands/login.js +26 -0
  46. package/dist/commands/login.js.map +1 -0
  47. package/dist/commands/scrub.js +42 -0
  48. package/dist/commands/scrub.js.map +1 -0
  49. package/dist/commands/transcripts.js +60 -0
  50. package/dist/commands/transcripts.js.map +1 -0
  51. package/package.json +28 -21
  52. package/dist/cli.cjs +0 -25240
  53. package/dist/cli.cjs.map +0 -1
  54. package/dist/cli.d.cts +0 -1
@@ -0,0 +1,4585 @@
1
+ import {
2
+ createPeerId,
3
+ createRoomCode,
4
+ resolveApiBaseUrl
5
+ } from "./chunk-XWVFKUUD.js";
6
+ import {
7
+ formatCngkitHelp
8
+ } from "./chunk-SSRUN6G5.js";
9
+ import {
10
+ __export
11
+ } from "./chunk-PZ5AY32C.js";
12
+
13
+ // src/command-actions.ts
14
+ import process4 from "process";
15
+
16
+ // ../../packages/client/src/generated/core/json.ts
17
+ var toJson = (value, replacer, space) => {
18
+ return JSON.stringify(value, replacer, space);
19
+ };
20
+ function fromJson(text, reviver) {
21
+ return JSON.parse(text, reviver);
22
+ }
23
+
24
+ // ../../packages/client/src/generated/errors/CngApiError.ts
25
+ var CngApiError = class extends Error {
26
+ statusCode;
27
+ body;
28
+ rawResponse;
29
+ cause;
30
+ constructor({
31
+ message,
32
+ statusCode,
33
+ body,
34
+ rawResponse,
35
+ cause
36
+ }) {
37
+ super(buildMessage({ message, statusCode, body }));
38
+ Object.setPrototypeOf(this, new.target.prototype);
39
+ if (Error.captureStackTrace) {
40
+ Error.captureStackTrace(this, this.constructor);
41
+ }
42
+ this.name = "CngApiError";
43
+ this.statusCode = statusCode;
44
+ this.body = body;
45
+ this.rawResponse = rawResponse;
46
+ if (cause != null) {
47
+ this.cause = cause;
48
+ }
49
+ }
50
+ };
51
+ function buildMessage({
52
+ message,
53
+ statusCode,
54
+ body
55
+ }) {
56
+ const lines = [];
57
+ if (message != null) {
58
+ lines.push(message);
59
+ }
60
+ if (statusCode != null) {
61
+ lines.push(`Status code: ${statusCode.toString()}`);
62
+ }
63
+ if (body != null) {
64
+ lines.push(`Body: ${toJson(body, void 0, 2)}`);
65
+ }
66
+ return lines.join("\n");
67
+ }
68
+
69
+ // ../../packages/client/src/generated/errors/CngApiTimeoutError.ts
70
+ var CngApiTimeoutError = class extends Error {
71
+ cause;
72
+ constructor(message, opts) {
73
+ super(message);
74
+ Object.setPrototypeOf(this, new.target.prototype);
75
+ if (Error.captureStackTrace) {
76
+ Error.captureStackTrace(this, this.constructor);
77
+ }
78
+ this.name = "CngApiTimeoutError";
79
+ if (opts?.cause != null) {
80
+ this.cause = opts.cause;
81
+ }
82
+ }
83
+ };
84
+
85
+ // ../../packages/client/src/generated/api/errors/BadGatewayError.ts
86
+ var BadGatewayError = class extends CngApiError {
87
+ constructor(body, rawResponse) {
88
+ super({
89
+ message: "BadGatewayError",
90
+ statusCode: 502,
91
+ body,
92
+ rawResponse
93
+ });
94
+ Object.setPrototypeOf(this, new.target.prototype);
95
+ if (Error.captureStackTrace) {
96
+ Error.captureStackTrace(this, this.constructor);
97
+ }
98
+ this.name = "BadGatewayError";
99
+ }
100
+ };
101
+
102
+ // ../../packages/client/src/generated/api/errors/BadRequestError.ts
103
+ var BadRequestError = class extends CngApiError {
104
+ constructor(body, rawResponse) {
105
+ super({
106
+ message: "BadRequestError",
107
+ statusCode: 400,
108
+ body,
109
+ rawResponse
110
+ });
111
+ Object.setPrototypeOf(this, new.target.prototype);
112
+ if (Error.captureStackTrace) {
113
+ Error.captureStackTrace(this, this.constructor);
114
+ }
115
+ this.name = "BadRequestError";
116
+ }
117
+ };
118
+
119
+ // ../../packages/client/src/generated/api/errors/ConflictError.ts
120
+ var ConflictError = class extends CngApiError {
121
+ constructor(body, rawResponse) {
122
+ super({
123
+ message: "ConflictError",
124
+ statusCode: 409,
125
+ body,
126
+ rawResponse
127
+ });
128
+ Object.setPrototypeOf(this, new.target.prototype);
129
+ if (Error.captureStackTrace) {
130
+ Error.captureStackTrace(this, this.constructor);
131
+ }
132
+ this.name = "ConflictError";
133
+ }
134
+ };
135
+
136
+ // ../../packages/client/src/generated/api/errors/ContentTooLargeError.ts
137
+ var ContentTooLargeError = class extends CngApiError {
138
+ constructor(body, rawResponse) {
139
+ super({
140
+ message: "ContentTooLargeError",
141
+ statusCode: 413,
142
+ body,
143
+ rawResponse
144
+ });
145
+ Object.setPrototypeOf(this, new.target.prototype);
146
+ if (Error.captureStackTrace) {
147
+ Error.captureStackTrace(this, this.constructor);
148
+ }
149
+ this.name = "ContentTooLargeError";
150
+ }
151
+ };
152
+
153
+ // ../../packages/client/src/generated/api/errors/InternalServerError.ts
154
+ var InternalServerError = class extends CngApiError {
155
+ constructor(body, rawResponse) {
156
+ super({
157
+ message: "InternalServerError",
158
+ statusCode: 500,
159
+ body,
160
+ rawResponse
161
+ });
162
+ Object.setPrototypeOf(this, new.target.prototype);
163
+ if (Error.captureStackTrace) {
164
+ Error.captureStackTrace(this, this.constructor);
165
+ }
166
+ this.name = "InternalServerError";
167
+ }
168
+ };
169
+
170
+ // ../../packages/client/src/generated/api/errors/NotFoundError.ts
171
+ var NotFoundError = class extends CngApiError {
172
+ constructor(body, rawResponse) {
173
+ super({
174
+ message: "NotFoundError",
175
+ statusCode: 404,
176
+ body,
177
+ rawResponse
178
+ });
179
+ Object.setPrototypeOf(this, new.target.prototype);
180
+ if (Error.captureStackTrace) {
181
+ Error.captureStackTrace(this, this.constructor);
182
+ }
183
+ this.name = "NotFoundError";
184
+ }
185
+ };
186
+
187
+ // ../../packages/client/src/generated/api/errors/ServiceUnavailableError.ts
188
+ var ServiceUnavailableError = class extends CngApiError {
189
+ constructor(body, rawResponse) {
190
+ super({
191
+ message: "ServiceUnavailableError",
192
+ statusCode: 503,
193
+ body,
194
+ rawResponse
195
+ });
196
+ Object.setPrototypeOf(this, new.target.prototype);
197
+ if (Error.captureStackTrace) {
198
+ Error.captureStackTrace(this, this.constructor);
199
+ }
200
+ this.name = "ServiceUnavailableError";
201
+ }
202
+ };
203
+
204
+ // ../../packages/client/src/generated/api/errors/UnauthorizedError.ts
205
+ var UnauthorizedError = class extends CngApiError {
206
+ constructor(body, rawResponse) {
207
+ super({
208
+ message: "UnauthorizedError",
209
+ statusCode: 401,
210
+ body,
211
+ rawResponse
212
+ });
213
+ Object.setPrototypeOf(this, new.target.prototype);
214
+ if (Error.captureStackTrace) {
215
+ Error.captureStackTrace(this, this.constructor);
216
+ }
217
+ this.name = "UnauthorizedError";
218
+ }
219
+ };
220
+
221
+ // ../../packages/client/src/generated/api/resources/llm/client/requests/CreateLlmChatRequest.ts
222
+ var CreateLlmChatRequest;
223
+ ((CreateLlmChatRequest2) => {
224
+ let Messages;
225
+ ((Messages2) => {
226
+ let Item;
227
+ ((Item2) => {
228
+ Item2.Role = {
229
+ System: "system",
230
+ User: "user",
231
+ Assistant: "assistant"
232
+ };
233
+ let Parts;
234
+ ((Parts2) => {
235
+ let Item3;
236
+ ((Item4) => {
237
+ Item4.Type = {
238
+ Text: "text"
239
+ };
240
+ Item4.State = {
241
+ Streaming: "streaming",
242
+ Done: "done"
243
+ };
244
+ })(Item3 = Parts2.Item || (Parts2.Item = {}));
245
+ })(Parts = Item2.Parts || (Item2.Parts = {}));
246
+ })(Item = Messages2.Item || (Messages2.Item = {}));
247
+ })(Messages = CreateLlmChatRequest2.Messages || (CreateLlmChatRequest2.Messages = {}));
248
+ })(CreateLlmChatRequest || (CreateLlmChatRequest = {}));
249
+
250
+ // ../../packages/client/src/generated/api/resources/llm/types/GetLlmHealthResponse.ts
251
+ var GetLlmHealthResponse;
252
+ ((GetLlmHealthResponse2) => {
253
+ GetLlmHealthResponse2.Service = {
254
+ CurlyNgBackend: "curly-ng-backend"
255
+ };
256
+ GetLlmHealthResponse2.Model = {
257
+ CfGoogleGemma426Ba4BIt: "@cf/google/gemma-4-26b-a4b-it"
258
+ };
259
+ })(GetLlmHealthResponse || (GetLlmHealthResponse = {}));
260
+
261
+ // ../../packages/client/src/generated/api/resources/system/types/GetHealthResponse.ts
262
+ var GetHealthResponse;
263
+ ((GetHealthResponse2) => {
264
+ GetHealthResponse2.Service = {
265
+ CurlyNgBackend: "curly-ng-backend"
266
+ };
267
+ })(GetHealthResponse || (GetHealthResponse = {}));
268
+
269
+ // ../../packages/client/src/generated/api/resources/telemetry/client/requests/NavigationEventRequest.ts
270
+ var NavigationEventRequest;
271
+ ((NavigationEventRequest2) => {
272
+ NavigationEventRequest2.EventType = {
273
+ PageView: "page_view",
274
+ Interaction: "interaction"
275
+ };
276
+ NavigationEventRequest2.InteractionType = {
277
+ Click: "click",
278
+ Submit: "submit"
279
+ };
280
+ })(NavigationEventRequest || (NavigationEventRequest = {}));
281
+
282
+ // ../../packages/client/src/generated/api/types/HarnessCatalogSummary.ts
283
+ var HarnessCatalogSummary;
284
+ ((HarnessCatalogSummary2) => {
285
+ HarnessCatalogSummary2.Name = {
286
+ CurlyHarness: "curly-harness"
287
+ };
288
+ })(HarnessCatalogSummary || (HarnessCatalogSummary = {}));
289
+
290
+ // ../../packages/client/src/generated/api/types/HarnessSemanticSearchResponse.ts
291
+ var HarnessSemanticSearchResponse;
292
+ ((HarnessSemanticSearchResponse2) => {
293
+ HarnessSemanticSearchResponse2.Model = {
294
+ CfBaaiBgeBaseEnV15: "@cf/baai/bge-base-en-v1.5"
295
+ };
296
+ })(HarnessSemanticSearchResponse || (HarnessSemanticSearchResponse = {}));
297
+
298
+ // ../../packages/client/src/generated/api/types/HarnessVectorizeBinding.ts
299
+ var HarnessVectorizeBinding;
300
+ ((HarnessVectorizeBinding2) => {
301
+ HarnessVectorizeBinding2.Index = {
302
+ CurlyNgAgents: "curly-ng-agents"
303
+ };
304
+ HarnessVectorizeBinding2.Binding = {
305
+ Vectorize: "VECTORIZE"
306
+ };
307
+ })(HarnessVectorizeBinding || (HarnessVectorizeBinding = {}));
308
+
309
+ // ../../packages/client/src/generated/core/headers.ts
310
+ function mergeHeaders(...headersArray) {
311
+ const result = {};
312
+ for (const [key, value] of headersArray.filter((headers) => headers != null).flatMap((headers) => Object.entries(headers))) {
313
+ const insensitiveKey = key.toLowerCase();
314
+ if (value != null) {
315
+ result[insensitiveKey] = value;
316
+ } else if (insensitiveKey in result) {
317
+ delete result[insensitiveKey];
318
+ }
319
+ }
320
+ return result;
321
+ }
322
+
323
+ // ../../packages/client/src/generated/core/fetcher/EndpointSupplier.ts
324
+ var EndpointSupplier = {
325
+ get: async (supplier, arg) => {
326
+ if (typeof supplier === "function") {
327
+ return supplier(arg);
328
+ } else {
329
+ return supplier;
330
+ }
331
+ }
332
+ };
333
+
334
+ // ../../packages/client/src/generated/core/logging/logger.ts
335
+ var LogLevel = {
336
+ Debug: "debug",
337
+ Info: "info",
338
+ Warn: "warn",
339
+ Error: "error"
340
+ };
341
+ var logLevelMap = {
342
+ [LogLevel.Debug]: 1,
343
+ [LogLevel.Info]: 2,
344
+ [LogLevel.Warn]: 3,
345
+ [LogLevel.Error]: 4
346
+ };
347
+ var ConsoleLogger = class {
348
+ debug(message, ...args) {
349
+ console.debug(message, ...args);
350
+ }
351
+ info(message, ...args) {
352
+ console.info(message, ...args);
353
+ }
354
+ warn(message, ...args) {
355
+ console.warn(message, ...args);
356
+ }
357
+ error(message, ...args) {
358
+ console.error(message, ...args);
359
+ }
360
+ };
361
+ var Logger = class {
362
+ level;
363
+ logger;
364
+ silent;
365
+ /**
366
+ * Creates a new logger instance.
367
+ * @param config - Logger configuration
368
+ */
369
+ constructor(config) {
370
+ this.level = logLevelMap[config.level];
371
+ this.logger = config.logger;
372
+ this.silent = config.silent;
373
+ }
374
+ /**
375
+ * Checks if a log level should be output based on configuration.
376
+ * @param level - The log level to check
377
+ * @returns True if the level should be logged
378
+ */
379
+ shouldLog(level) {
380
+ return !this.silent && this.level <= logLevelMap[level];
381
+ }
382
+ /**
383
+ * Checks if debug logging is enabled.
384
+ * @returns True if debug logs should be output
385
+ */
386
+ isDebug() {
387
+ return this.shouldLog(LogLevel.Debug);
388
+ }
389
+ /**
390
+ * Logs a debug message if debug logging is enabled.
391
+ * @param message - The message to log
392
+ * @param args - Additional arguments to log
393
+ */
394
+ debug(message, ...args) {
395
+ if (this.isDebug()) {
396
+ this.logger.debug(message, ...args);
397
+ }
398
+ }
399
+ /**
400
+ * Checks if info logging is enabled.
401
+ * @returns True if info logs should be output
402
+ */
403
+ isInfo() {
404
+ return this.shouldLog(LogLevel.Info);
405
+ }
406
+ /**
407
+ * Logs an info message if info logging is enabled.
408
+ * @param message - The message to log
409
+ * @param args - Additional arguments to log
410
+ */
411
+ info(message, ...args) {
412
+ if (this.isInfo()) {
413
+ this.logger.info(message, ...args);
414
+ }
415
+ }
416
+ /**
417
+ * Checks if warning logging is enabled.
418
+ * @returns True if warning logs should be output
419
+ */
420
+ isWarn() {
421
+ return this.shouldLog(LogLevel.Warn);
422
+ }
423
+ /**
424
+ * Logs a warning message if warning logging is enabled.
425
+ * @param message - The message to log
426
+ * @param args - Additional arguments to log
427
+ */
428
+ warn(message, ...args) {
429
+ if (this.isWarn()) {
430
+ this.logger.warn(message, ...args);
431
+ }
432
+ }
433
+ /**
434
+ * Checks if error logging is enabled.
435
+ * @returns True if error logs should be output
436
+ */
437
+ isError() {
438
+ return this.shouldLog(LogLevel.Error);
439
+ }
440
+ /**
441
+ * Logs an error message if error logging is enabled.
442
+ * @param message - The message to log
443
+ * @param args - Additional arguments to log
444
+ */
445
+ error(message, ...args) {
446
+ if (this.isError()) {
447
+ this.logger.error(message, ...args);
448
+ }
449
+ }
450
+ };
451
+ function createLogger(config) {
452
+ if (config == null) {
453
+ return defaultLogger;
454
+ }
455
+ if (config instanceof Logger) {
456
+ return config;
457
+ }
458
+ config = config ?? {};
459
+ config.level ??= LogLevel.Info;
460
+ config.logger ??= new ConsoleLogger();
461
+ config.silent ??= true;
462
+ return new Logger(config);
463
+ }
464
+ var defaultLogger = new Logger({
465
+ level: LogLevel.Info,
466
+ logger: new ConsoleLogger(),
467
+ silent: true
468
+ });
469
+
470
+ // ../../packages/client/src/generated/core/url/qs.ts
471
+ var defaultQsOptions = {
472
+ arrayFormat: "indices",
473
+ encode: true
474
+ };
475
+ function encodeValue(value, shouldEncode) {
476
+ if (value === void 0) {
477
+ return "";
478
+ }
479
+ if (value === null) {
480
+ return "";
481
+ }
482
+ const stringValue = String(value);
483
+ return shouldEncode ? encodeURIComponent(stringValue) : stringValue;
484
+ }
485
+ function stringifyObject(obj, prefix = "", options) {
486
+ const parts = [];
487
+ for (const [key, value] of Object.entries(obj)) {
488
+ const fullKey = prefix ? `${prefix}[${key}]` : key;
489
+ if (value === void 0) {
490
+ continue;
491
+ }
492
+ if (Array.isArray(value)) {
493
+ if (value.length === 0) {
494
+ continue;
495
+ }
496
+ const effectiveFormat = options.arrayFormat;
497
+ if (effectiveFormat === "comma") {
498
+ const encodedKey = options.encode ? encodeURIComponent(fullKey) : fullKey;
499
+ const encodedValues = value.filter((item) => item !== void 0 && item !== null).map((item) => encodeValue(item, options.encode));
500
+ if (encodedValues.length > 0) {
501
+ parts.push(`${encodedKey}=${encodedValues.join(",")}`);
502
+ }
503
+ } else {
504
+ for (let i = 0; i < value.length; i++) {
505
+ const item = value[i];
506
+ if (item === void 0) {
507
+ continue;
508
+ }
509
+ if (typeof item === "object" && !Array.isArray(item) && item !== null) {
510
+ const arrayKey = effectiveFormat === "indices" ? `${fullKey}[${i}]` : fullKey;
511
+ parts.push(...stringifyObject(item, arrayKey, options));
512
+ } else {
513
+ const arrayKey = effectiveFormat === "indices" ? `${fullKey}[${i}]` : fullKey;
514
+ const encodedKey = options.encode ? encodeURIComponent(arrayKey) : arrayKey;
515
+ parts.push(`${encodedKey}=${encodeValue(item, options.encode)}`);
516
+ }
517
+ }
518
+ }
519
+ } else if (typeof value === "object" && value !== null) {
520
+ if (Object.keys(value).length === 0) {
521
+ continue;
522
+ }
523
+ parts.push(...stringifyObject(value, fullKey, options));
524
+ } else {
525
+ const encodedKey = options.encode ? encodeURIComponent(fullKey) : fullKey;
526
+ parts.push(`${encodedKey}=${encodeValue(value, options.encode)}`);
527
+ }
528
+ }
529
+ return parts;
530
+ }
531
+ function toQueryString(obj, options) {
532
+ if (obj == null || typeof obj !== "object") {
533
+ return "";
534
+ }
535
+ const parts = stringifyObject(obj, "", {
536
+ ...defaultQsOptions,
537
+ ...options
538
+ });
539
+ return parts.join("&");
540
+ }
541
+
542
+ // ../../packages/client/src/generated/core/fetcher/createRequestUrl.ts
543
+ function createRequestUrl(baseUrl, queryParameters) {
544
+ const queryString = toQueryString(queryParameters, { arrayFormat: "repeat" });
545
+ return queryString ? `${baseUrl}?${queryString}` : baseUrl;
546
+ }
547
+
548
+ // ../../packages/client/src/generated/core/fetcher/BinaryResponse.ts
549
+ function getBinaryResponse(response) {
550
+ const binaryResponse = {
551
+ get bodyUsed() {
552
+ return response.bodyUsed;
553
+ },
554
+ stream: () => response.body,
555
+ arrayBuffer: response.arrayBuffer.bind(response),
556
+ blob: response.blob.bind(response)
557
+ };
558
+ if ("bytes" in response && typeof response.bytes === "function") {
559
+ binaryResponse.bytes = response.bytes.bind(response);
560
+ }
561
+ return binaryResponse;
562
+ }
563
+
564
+ // ../../packages/client/src/generated/core/fetcher/getResponseBody.ts
565
+ function retainResponse(target, response) {
566
+ Object.defineProperty(target, "__fern_response_ref", {
567
+ value: response,
568
+ enumerable: false,
569
+ configurable: true,
570
+ writable: false
571
+ });
572
+ }
573
+ async function getResponseBody(response, responseType) {
574
+ switch (responseType) {
575
+ case "binary-response":
576
+ return getBinaryResponse(response);
577
+ case "blob":
578
+ return await response.blob();
579
+ case "arrayBuffer":
580
+ return await response.arrayBuffer();
581
+ case "sse":
582
+ if (response.body == null) {
583
+ return {
584
+ ok: false,
585
+ error: {
586
+ reason: "body-is-null",
587
+ statusCode: response.status
588
+ }
589
+ };
590
+ }
591
+ retainResponse(response.body, response);
592
+ return response.body;
593
+ case "streaming":
594
+ if (response.body == null) {
595
+ return {
596
+ ok: false,
597
+ error: {
598
+ reason: "body-is-null",
599
+ statusCode: response.status
600
+ }
601
+ };
602
+ }
603
+ retainResponse(response.body, response);
604
+ return response.body;
605
+ case "text":
606
+ return await response.text();
607
+ }
608
+ const text = await response.text();
609
+ if (text.length > 0) {
610
+ try {
611
+ const responseBody = fromJson(text);
612
+ return responseBody;
613
+ } catch (_err) {
614
+ return {
615
+ ok: false,
616
+ error: {
617
+ reason: "non-json",
618
+ statusCode: response.status,
619
+ rawBody: text
620
+ }
621
+ };
622
+ }
623
+ }
624
+ return void 0;
625
+ }
626
+
627
+ // ../../packages/client/src/generated/core/fetcher/getErrorResponseBody.ts
628
+ async function getErrorResponseBody(response) {
629
+ let contentType = response.headers.get("Content-Type")?.toLowerCase();
630
+ if (contentType == null || contentType.length === 0) {
631
+ return getResponseBody(response);
632
+ }
633
+ if (contentType.indexOf(";") !== -1) {
634
+ contentType = contentType.split(";")[0]?.trim() ?? "";
635
+ }
636
+ switch (contentType) {
637
+ case "application/hal+json":
638
+ case "application/json":
639
+ case "application/ld+json":
640
+ case "application/problem+json":
641
+ case "application/vnd.api+json":
642
+ case "text/json": {
643
+ const text = await response.text();
644
+ return text.length > 0 ? fromJson(text) : void 0;
645
+ }
646
+ default:
647
+ if (contentType.startsWith("application/vnd.") && contentType.endsWith("+json")) {
648
+ const text = await response.text();
649
+ return text.length > 0 ? fromJson(text) : void 0;
650
+ }
651
+ return await response.text();
652
+ }
653
+ }
654
+
655
+ // ../../packages/client/src/generated/core/fetcher/getFetchFn.ts
656
+ async function getFetchFn() {
657
+ return fetch;
658
+ }
659
+
660
+ // ../../packages/client/src/generated/core/fetcher/getRequestBody.ts
661
+ async function getRequestBody({ body, type }) {
662
+ if (type === "form") {
663
+ return toQueryString(body, { arrayFormat: "repeat", encode: true });
664
+ }
665
+ if (type.includes("json")) {
666
+ return toJson(body);
667
+ } else {
668
+ return body;
669
+ }
670
+ }
671
+
672
+ // ../../packages/client/src/generated/core/fetcher/Headers.ts
673
+ var Headers2;
674
+ if (typeof globalThis.Headers !== "undefined") {
675
+ Headers2 = globalThis.Headers;
676
+ } else {
677
+ Headers2 = class Headers3 {
678
+ headers;
679
+ constructor(init) {
680
+ this.headers = /* @__PURE__ */ new Map();
681
+ if (init) {
682
+ if (init instanceof Headers3) {
683
+ init.forEach((value, key) => this.append(key, value));
684
+ } else if (Array.isArray(init)) {
685
+ for (const [key, value] of init) {
686
+ if (typeof key === "string" && typeof value === "string") {
687
+ this.append(key, value);
688
+ } else {
689
+ throw new TypeError("Each header entry must be a [string, string] tuple");
690
+ }
691
+ }
692
+ } else {
693
+ for (const [key, value] of Object.entries(init)) {
694
+ if (typeof value === "string") {
695
+ this.append(key, value);
696
+ } else {
697
+ throw new TypeError("Header values must be strings");
698
+ }
699
+ }
700
+ }
701
+ }
702
+ }
703
+ append(name, value) {
704
+ const key = name.toLowerCase();
705
+ const existing = this.headers.get(key) || [];
706
+ this.headers.set(key, [...existing, value]);
707
+ }
708
+ delete(name) {
709
+ const key = name.toLowerCase();
710
+ this.headers.delete(key);
711
+ }
712
+ get(name) {
713
+ const key = name.toLowerCase();
714
+ const values = this.headers.get(key);
715
+ return values ? values.join(", ") : null;
716
+ }
717
+ has(name) {
718
+ const key = name.toLowerCase();
719
+ return this.headers.has(key);
720
+ }
721
+ set(name, value) {
722
+ const key = name.toLowerCase();
723
+ this.headers.set(key, [value]);
724
+ }
725
+ forEach(callbackfn, thisArg) {
726
+ const boundCallback = thisArg ? callbackfn.bind(thisArg) : callbackfn;
727
+ this.headers.forEach((values, key) => boundCallback(values.join(", "), key, this));
728
+ }
729
+ getSetCookie() {
730
+ return this.headers.get("set-cookie") || [];
731
+ }
732
+ *entries() {
733
+ for (const [key, values] of this.headers.entries()) {
734
+ yield [key, values.join(", ")];
735
+ }
736
+ }
737
+ *keys() {
738
+ yield* this.headers.keys();
739
+ }
740
+ *values() {
741
+ for (const values of this.headers.values()) {
742
+ yield values.join(", ");
743
+ }
744
+ }
745
+ [Symbol.iterator]() {
746
+ return this.entries();
747
+ }
748
+ };
749
+ }
750
+
751
+ // ../../packages/client/src/generated/core/fetcher/signals.ts
752
+ var TIMEOUT = "timeout";
753
+ function getTimeoutSignal(timeoutMs) {
754
+ const controller = new AbortController();
755
+ const abortId = setTimeout(() => controller.abort(TIMEOUT), timeoutMs);
756
+ return { signal: controller.signal, abortId };
757
+ }
758
+ function anySignal(...args) {
759
+ const signals = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;
760
+ const controller = new AbortController();
761
+ for (const signal of signals) {
762
+ if (signal.aborted) {
763
+ controller.abort(signal?.reason);
764
+ return controller.signal;
765
+ }
766
+ signal.addEventListener("abort", () => controller.abort(signal?.reason), {
767
+ signal: controller.signal
768
+ });
769
+ if (signal.aborted) {
770
+ controller.abort(signal?.reason);
771
+ return controller.signal;
772
+ }
773
+ }
774
+ return controller.signal;
775
+ }
776
+
777
+ // ../../packages/client/src/generated/core/fetcher/makeRequest.ts
778
+ var _cacheNoStoreSupported;
779
+ function isCacheNoStoreSupported() {
780
+ if (_cacheNoStoreSupported != null) {
781
+ return _cacheNoStoreSupported;
782
+ }
783
+ try {
784
+ new Request("http://localhost", { cache: "no-store" });
785
+ _cacheNoStoreSupported = true;
786
+ } catch {
787
+ _cacheNoStoreSupported = false;
788
+ }
789
+ return _cacheNoStoreSupported;
790
+ }
791
+ var makeRequest = async (fetchFn, url, method, headers, requestBody, timeoutMs, abortSignal, withCredentials, duplex, disableCache) => {
792
+ const signals = [];
793
+ let timeoutAbortId;
794
+ if (timeoutMs != null) {
795
+ const { signal, abortId } = getTimeoutSignal(timeoutMs);
796
+ timeoutAbortId = abortId;
797
+ signals.push(signal);
798
+ }
799
+ if (abortSignal != null) {
800
+ signals.push(abortSignal);
801
+ }
802
+ const newSignals = anySignal(signals);
803
+ const response = await fetchFn(url, {
804
+ method,
805
+ headers,
806
+ body: requestBody,
807
+ signal: newSignals,
808
+ credentials: withCredentials ? "include" : void 0,
809
+ // @ts-ignore
810
+ duplex,
811
+ ...disableCache && isCacheNoStoreSupported() ? { cache: "no-store" } : {}
812
+ });
813
+ if (timeoutAbortId != null) {
814
+ clearTimeout(timeoutAbortId);
815
+ }
816
+ return response;
817
+ };
818
+
819
+ // ../../packages/client/src/generated/core/fetcher/RawResponse.ts
820
+ var abortRawResponse = {
821
+ headers: new Headers2(),
822
+ redirected: false,
823
+ status: 499,
824
+ statusText: "Client Closed Request",
825
+ type: "error",
826
+ url: ""
827
+ };
828
+ var unknownRawResponse = {
829
+ headers: new Headers2(),
830
+ redirected: false,
831
+ status: 0,
832
+ statusText: "Unknown Error",
833
+ type: "error",
834
+ url: ""
835
+ };
836
+ function toRawResponse(response) {
837
+ return {
838
+ headers: response.headers,
839
+ redirected: response.redirected,
840
+ status: response.status,
841
+ statusText: response.statusText,
842
+ type: response.type,
843
+ url: response.url
844
+ };
845
+ }
846
+
847
+ // ../../packages/client/src/generated/core/fetcher/requestWithRetries.ts
848
+ var INITIAL_RETRY_DELAY = 1e3;
849
+ var MAX_RETRY_DELAY = 6e4;
850
+ var DEFAULT_MAX_RETRIES = 2;
851
+ var JITTER_FACTOR = 0.2;
852
+ function isRetryableStatusCode(statusCode) {
853
+ return [408, 429].includes(statusCode) || statusCode >= 500;
854
+ }
855
+ function addPositiveJitter(delay) {
856
+ const jitterMultiplier = 1 + Math.random() * JITTER_FACTOR;
857
+ return delay * jitterMultiplier;
858
+ }
859
+ function addSymmetricJitter(delay) {
860
+ const jitterMultiplier = 1 + (Math.random() - 0.5) * JITTER_FACTOR;
861
+ return delay * jitterMultiplier;
862
+ }
863
+ function getRetryDelayFromHeaders(response, retryAttempt) {
864
+ const retryAfter = response.headers.get("Retry-After");
865
+ if (retryAfter) {
866
+ const retryAfterSeconds = parseInt(retryAfter, 10);
867
+ if (!Number.isNaN(retryAfterSeconds) && retryAfterSeconds > 0) {
868
+ return Math.min(retryAfterSeconds * 1e3, MAX_RETRY_DELAY);
869
+ }
870
+ const retryAfterDate = new Date(retryAfter);
871
+ if (!Number.isNaN(retryAfterDate.getTime())) {
872
+ const delay = retryAfterDate.getTime() - Date.now();
873
+ if (delay > 0) {
874
+ return Math.min(Math.max(delay, 0), MAX_RETRY_DELAY);
875
+ }
876
+ }
877
+ }
878
+ const rateLimitReset = response.headers.get("X-RateLimit-Reset");
879
+ if (rateLimitReset) {
880
+ const resetTime = parseInt(rateLimitReset, 10);
881
+ if (!Number.isNaN(resetTime)) {
882
+ const delay = resetTime * 1e3 - Date.now();
883
+ if (delay > 0) {
884
+ return addPositiveJitter(Math.min(delay, MAX_RETRY_DELAY));
885
+ }
886
+ }
887
+ }
888
+ return addSymmetricJitter(Math.min(INITIAL_RETRY_DELAY * 2 ** retryAttempt, MAX_RETRY_DELAY));
889
+ }
890
+ async function requestWithRetries(requestFn, maxRetries = DEFAULT_MAX_RETRIES) {
891
+ let response = await requestFn();
892
+ for (let i = 0; i < maxRetries; ++i) {
893
+ if (isRetryableStatusCode(response.status)) {
894
+ const delay = getRetryDelayFromHeaders(response, i);
895
+ await new Promise((resolve) => setTimeout(resolve, delay));
896
+ response = await requestFn();
897
+ } else {
898
+ break;
899
+ }
900
+ }
901
+ return response;
902
+ }
903
+
904
+ // ../../packages/client/src/generated/core/fetcher/Fetcher.ts
905
+ var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
906
+ "authorization",
907
+ "www-authenticate",
908
+ "x-api-key",
909
+ "api-key",
910
+ "apikey",
911
+ "x-api-token",
912
+ "x-auth-token",
913
+ "auth-token",
914
+ "cookie",
915
+ "set-cookie",
916
+ "proxy-authorization",
917
+ "proxy-authenticate",
918
+ "x-csrf-token",
919
+ "x-xsrf-token",
920
+ "x-session-token",
921
+ "x-access-token"
922
+ ]);
923
+ function redactHeaders(headers) {
924
+ const filtered = {};
925
+ for (const [key, value] of headers instanceof Headers2 ? headers.entries() : Object.entries(headers)) {
926
+ if (SENSITIVE_HEADERS.has(key.toLowerCase())) {
927
+ filtered[key] = "[REDACTED]";
928
+ } else {
929
+ filtered[key] = value;
930
+ }
931
+ }
932
+ return filtered;
933
+ }
934
+ var SENSITIVE_QUERY_PARAMS = /* @__PURE__ */ new Set([
935
+ "api_key",
936
+ "api-key",
937
+ "apikey",
938
+ "token",
939
+ "access_token",
940
+ "access-token",
941
+ "auth_token",
942
+ "auth-token",
943
+ "password",
944
+ "passwd",
945
+ "secret",
946
+ "api_secret",
947
+ "api-secret",
948
+ "apisecret",
949
+ "key",
950
+ "session",
951
+ "session_id",
952
+ "session-id"
953
+ ]);
954
+ function redactQueryParameters(queryParameters) {
955
+ if (queryParameters == null) {
956
+ return void 0;
957
+ }
958
+ const redacted = {};
959
+ for (const [key, value] of Object.entries(queryParameters)) {
960
+ redacted[key] = SENSITIVE_QUERY_PARAMS.has(key.toLowerCase()) ? "[REDACTED]" : value;
961
+ }
962
+ return redacted;
963
+ }
964
+ function redactUrl(url) {
965
+ const protocolIndex = url.indexOf("://");
966
+ if (protocolIndex === -1) return url;
967
+ const afterProtocol = protocolIndex + 3;
968
+ const pathStart = url.indexOf("/", afterProtocol);
969
+ let queryStart = url.indexOf("?", afterProtocol);
970
+ let fragmentStart = url.indexOf("#", afterProtocol);
971
+ const firstDelimiter = Math.min(
972
+ pathStart === -1 ? url.length : pathStart,
973
+ queryStart === -1 ? url.length : queryStart,
974
+ fragmentStart === -1 ? url.length : fragmentStart
975
+ );
976
+ let atIndex = -1;
977
+ for (let i = afterProtocol; i < firstDelimiter; i++) {
978
+ if (url[i] === "@") {
979
+ atIndex = i;
980
+ }
981
+ }
982
+ if (atIndex !== -1) {
983
+ url = `${url.slice(0, afterProtocol)}[REDACTED]@${url.slice(atIndex + 1)}`;
984
+ }
985
+ queryStart = url.indexOf("?");
986
+ if (queryStart === -1) return url;
987
+ fragmentStart = url.indexOf("#", queryStart);
988
+ const queryEnd = fragmentStart !== -1 ? fragmentStart : url.length;
989
+ const queryString = url.slice(queryStart + 1, queryEnd);
990
+ if (queryString.length === 0) return url;
991
+ const lower = queryString.toLowerCase();
992
+ const hasSensitive = lower.includes("token") || lower.includes("key") || lower.includes("password") || lower.includes("passwd") || lower.includes("secret") || lower.includes("session") || lower.includes("auth");
993
+ if (!hasSensitive) {
994
+ return url;
995
+ }
996
+ const redactedParams = [];
997
+ const params = queryString.split("&");
998
+ for (const param of params) {
999
+ const equalIndex = param.indexOf("=");
1000
+ if (equalIndex === -1) {
1001
+ redactedParams.push(param);
1002
+ continue;
1003
+ }
1004
+ const key = param.slice(0, equalIndex);
1005
+ let shouldRedact = SENSITIVE_QUERY_PARAMS.has(key.toLowerCase());
1006
+ if (!shouldRedact && key.includes("%")) {
1007
+ try {
1008
+ const decodedKey = decodeURIComponent(key);
1009
+ shouldRedact = SENSITIVE_QUERY_PARAMS.has(decodedKey.toLowerCase());
1010
+ } catch {
1011
+ }
1012
+ }
1013
+ redactedParams.push(shouldRedact ? `${key}=[REDACTED]` : param);
1014
+ }
1015
+ return url.slice(0, queryStart + 1) + redactedParams.join("&") + url.slice(queryEnd);
1016
+ }
1017
+ async function getHeaders(args) {
1018
+ const newHeaders = new Headers2();
1019
+ newHeaders.set(
1020
+ "Accept",
1021
+ args.responseType === "json" ? "application/json" : args.responseType === "text" ? "text/plain" : args.responseType === "sse" ? "text/event-stream" : "*/*"
1022
+ );
1023
+ if (args.body !== void 0 && args.contentType != null) {
1024
+ newHeaders.set("Content-Type", args.contentType);
1025
+ }
1026
+ if (args.headers == null) {
1027
+ return newHeaders;
1028
+ }
1029
+ for (const [key, value] of Object.entries(args.headers)) {
1030
+ const result = await EndpointSupplier.get(value, { endpointMetadata: args.endpointMetadata ?? {} });
1031
+ if (typeof result === "string") {
1032
+ newHeaders.set(key, result);
1033
+ continue;
1034
+ }
1035
+ if (result == null) {
1036
+ continue;
1037
+ }
1038
+ newHeaders.set(key, `${result}`);
1039
+ }
1040
+ return newHeaders;
1041
+ }
1042
+ async function fetcherImpl(args) {
1043
+ let url = args.url;
1044
+ if (args.queryString != null && args.queryString.length > 0) {
1045
+ url = `${url}?${args.queryString}`;
1046
+ } else {
1047
+ url = createRequestUrl(args.url, args.queryParameters);
1048
+ }
1049
+ const requestBody = await getRequestBody({
1050
+ body: args.body,
1051
+ type: args.requestType ?? "other"
1052
+ });
1053
+ const fetchFn = args.fetchFn ?? await getFetchFn();
1054
+ const headers = await getHeaders(args);
1055
+ const logger = createLogger(args.logging);
1056
+ if (logger.isDebug()) {
1057
+ const metadata = {
1058
+ method: args.method,
1059
+ url: redactUrl(url),
1060
+ headers: redactHeaders(headers),
1061
+ queryParameters: redactQueryParameters(args.queryParameters),
1062
+ hasBody: requestBody != null
1063
+ };
1064
+ logger.debug("Making HTTP request", metadata);
1065
+ }
1066
+ try {
1067
+ const response = await requestWithRetries(
1068
+ async () => makeRequest(
1069
+ fetchFn,
1070
+ url,
1071
+ args.method,
1072
+ headers,
1073
+ requestBody,
1074
+ args.timeoutMs,
1075
+ args.abortSignal,
1076
+ args.withCredentials,
1077
+ args.duplex,
1078
+ args.responseType === "streaming" || args.responseType === "sse"
1079
+ ),
1080
+ args.maxRetries
1081
+ );
1082
+ if (response.status >= 200 && response.status < 400) {
1083
+ if (logger.isDebug()) {
1084
+ const metadata = {
1085
+ method: args.method,
1086
+ url: redactUrl(url),
1087
+ statusCode: response.status,
1088
+ responseHeaders: redactHeaders(response.headers)
1089
+ };
1090
+ logger.debug("HTTP request succeeded", metadata);
1091
+ }
1092
+ const body = await getResponseBody(response, args.responseType);
1093
+ return {
1094
+ ok: true,
1095
+ body,
1096
+ headers: response.headers,
1097
+ rawResponse: toRawResponse(response)
1098
+ };
1099
+ } else {
1100
+ if (logger.isError()) {
1101
+ const metadata = {
1102
+ method: args.method,
1103
+ url: redactUrl(url),
1104
+ statusCode: response.status,
1105
+ responseHeaders: redactHeaders(Object.fromEntries(response.headers.entries()))
1106
+ };
1107
+ logger.error("HTTP request failed with error status", metadata);
1108
+ }
1109
+ return {
1110
+ ok: false,
1111
+ error: {
1112
+ reason: "status-code",
1113
+ statusCode: response.status,
1114
+ body: await getErrorResponseBody(response)
1115
+ },
1116
+ rawResponse: toRawResponse(response)
1117
+ };
1118
+ }
1119
+ } catch (error) {
1120
+ if (args.abortSignal?.aborted) {
1121
+ if (logger.isError()) {
1122
+ const metadata = {
1123
+ method: args.method,
1124
+ url: redactUrl(url)
1125
+ };
1126
+ logger.error("HTTP request was aborted", metadata);
1127
+ }
1128
+ return {
1129
+ ok: false,
1130
+ error: {
1131
+ reason: "unknown",
1132
+ errorMessage: "The user aborted a request",
1133
+ cause: error
1134
+ },
1135
+ rawResponse: abortRawResponse
1136
+ };
1137
+ } else if (error instanceof Error && error.name === "AbortError") {
1138
+ if (logger.isError()) {
1139
+ const metadata = {
1140
+ method: args.method,
1141
+ url: redactUrl(url),
1142
+ timeoutMs: args.timeoutMs
1143
+ };
1144
+ logger.error("HTTP request timed out", metadata);
1145
+ }
1146
+ return {
1147
+ ok: false,
1148
+ error: {
1149
+ reason: "timeout",
1150
+ cause: error
1151
+ },
1152
+ rawResponse: abortRawResponse
1153
+ };
1154
+ } else if (error instanceof Error) {
1155
+ if (logger.isError()) {
1156
+ const metadata = {
1157
+ method: args.method,
1158
+ url: redactUrl(url),
1159
+ errorMessage: error.message
1160
+ };
1161
+ logger.error("HTTP request failed with error", metadata);
1162
+ }
1163
+ return {
1164
+ ok: false,
1165
+ error: {
1166
+ reason: "unknown",
1167
+ errorMessage: error.message,
1168
+ cause: error
1169
+ },
1170
+ rawResponse: unknownRawResponse
1171
+ };
1172
+ }
1173
+ if (logger.isError()) {
1174
+ const metadata = {
1175
+ method: args.method,
1176
+ url: redactUrl(url),
1177
+ error: toJson(error)
1178
+ };
1179
+ logger.error("HTTP request failed with unknown error", metadata);
1180
+ }
1181
+ return {
1182
+ ok: false,
1183
+ error: {
1184
+ reason: "unknown",
1185
+ errorMessage: toJson(error),
1186
+ cause: error
1187
+ },
1188
+ rawResponse: unknownRawResponse
1189
+ };
1190
+ }
1191
+ }
1192
+ var fetcher = fetcherImpl;
1193
+
1194
+ // ../../packages/client/src/generated/core/fetcher/HttpResponsePromise.ts
1195
+ var HttpResponsePromise = class _HttpResponsePromise extends Promise {
1196
+ innerPromise;
1197
+ unwrappedPromise;
1198
+ constructor(promise) {
1199
+ super((resolve) => {
1200
+ resolve(void 0);
1201
+ });
1202
+ this.innerPromise = promise;
1203
+ }
1204
+ /**
1205
+ * Creates an `HttpResponsePromise` from a function that returns a promise.
1206
+ *
1207
+ * @param fn - A function that returns a promise resolving to a `WithRawResponse` object.
1208
+ * @param args - Arguments to pass to the function.
1209
+ * @returns An `HttpResponsePromise` instance.
1210
+ */
1211
+ static fromFunction(fn, ...args) {
1212
+ return new _HttpResponsePromise(fn(...args));
1213
+ }
1214
+ /**
1215
+ * Creates a function that returns an `HttpResponsePromise` from a function that returns a promise.
1216
+ *
1217
+ * @param fn - A function that returns a promise resolving to a `WithRawResponse` object.
1218
+ * @returns A function that returns an `HttpResponsePromise` instance.
1219
+ */
1220
+ static interceptFunction(fn) {
1221
+ return (...args) => {
1222
+ return _HttpResponsePromise.fromPromise(fn(...args));
1223
+ };
1224
+ }
1225
+ /**
1226
+ * Creates an `HttpResponsePromise` from an existing promise.
1227
+ *
1228
+ * @param promise - A promise resolving to a `WithRawResponse` object.
1229
+ * @returns An `HttpResponsePromise` instance.
1230
+ */
1231
+ static fromPromise(promise) {
1232
+ return new _HttpResponsePromise(promise);
1233
+ }
1234
+ /**
1235
+ * Creates an `HttpResponsePromise` from an executor function.
1236
+ *
1237
+ * @param executor - A function that takes resolve and reject callbacks to create a promise.
1238
+ * @returns An `HttpResponsePromise` instance.
1239
+ */
1240
+ static fromExecutor(executor) {
1241
+ const promise = new Promise(executor);
1242
+ return new _HttpResponsePromise(promise);
1243
+ }
1244
+ /**
1245
+ * Creates an `HttpResponsePromise` from a resolved result.
1246
+ *
1247
+ * @param result - A `WithRawResponse` object to resolve immediately.
1248
+ * @returns An `HttpResponsePromise` instance.
1249
+ */
1250
+ static fromResult(result) {
1251
+ const promise = Promise.resolve(result);
1252
+ return new _HttpResponsePromise(promise);
1253
+ }
1254
+ unwrap() {
1255
+ if (!this.unwrappedPromise) {
1256
+ this.unwrappedPromise = this.innerPromise.then(({ data }) => data);
1257
+ }
1258
+ return this.unwrappedPromise;
1259
+ }
1260
+ /** @inheritdoc */
1261
+ then(onfulfilled, onrejected) {
1262
+ return this.unwrap().then(onfulfilled, onrejected);
1263
+ }
1264
+ /** @inheritdoc */
1265
+ catch(onrejected) {
1266
+ return this.unwrap().catch(onrejected);
1267
+ }
1268
+ /** @inheritdoc */
1269
+ finally(onfinally) {
1270
+ return this.unwrap().finally(onfinally);
1271
+ }
1272
+ /**
1273
+ * Retrieves the data and raw response.
1274
+ *
1275
+ * @returns A promise resolving to a `WithRawResponse` object.
1276
+ */
1277
+ async withRawResponse() {
1278
+ return await this.innerPromise;
1279
+ }
1280
+ };
1281
+
1282
+ // ../../packages/client/src/generated/core/url/join.ts
1283
+ function join(base, ...segments) {
1284
+ if (!base) {
1285
+ return "";
1286
+ }
1287
+ if (segments.length === 0) {
1288
+ return base;
1289
+ }
1290
+ if (base.includes("://")) {
1291
+ let url;
1292
+ try {
1293
+ url = new URL(base);
1294
+ } catch {
1295
+ return joinPath(base, ...segments);
1296
+ }
1297
+ const lastSegment = segments[segments.length - 1];
1298
+ const shouldPreserveTrailingSlash = lastSegment?.endsWith("/");
1299
+ for (const segment of segments) {
1300
+ const cleanSegment = trimSlashes(segment);
1301
+ if (cleanSegment) {
1302
+ url.pathname = joinPathSegments(url.pathname, cleanSegment);
1303
+ }
1304
+ }
1305
+ if (shouldPreserveTrailingSlash && !url.pathname.endsWith("/")) {
1306
+ url.pathname += "/";
1307
+ }
1308
+ return url.toString();
1309
+ }
1310
+ return joinPath(base, ...segments);
1311
+ }
1312
+ function joinPath(base, ...segments) {
1313
+ if (segments.length === 0) {
1314
+ return base;
1315
+ }
1316
+ let result = base;
1317
+ const lastSegment = segments[segments.length - 1];
1318
+ const shouldPreserveTrailingSlash = lastSegment?.endsWith("/");
1319
+ for (const segment of segments) {
1320
+ const cleanSegment = trimSlashes(segment);
1321
+ if (cleanSegment) {
1322
+ result = joinPathSegments(result, cleanSegment);
1323
+ }
1324
+ }
1325
+ if (shouldPreserveTrailingSlash && !result.endsWith("/")) {
1326
+ result += "/";
1327
+ }
1328
+ return result;
1329
+ }
1330
+ function joinPathSegments(left, right) {
1331
+ if (left.endsWith("/")) {
1332
+ return left + right;
1333
+ }
1334
+ return `${left}/${right}`;
1335
+ }
1336
+ function trimSlashes(str) {
1337
+ if (!str) return str;
1338
+ let start = 0;
1339
+ let end = str.length;
1340
+ if (str.startsWith("/")) start = 1;
1341
+ if (str.endsWith("/")) end = str.length - 1;
1342
+ return start === 0 && end === str.length ? str : str.slice(start, end);
1343
+ }
1344
+
1345
+ // ../../packages/client/src/generated/core/fetcher/Supplier.ts
1346
+ var Supplier = {
1347
+ get: async (supplier) => {
1348
+ if (typeof supplier === "function") {
1349
+ return supplier();
1350
+ } else {
1351
+ return supplier;
1352
+ }
1353
+ }
1354
+ };
1355
+
1356
+ // ../../packages/client/src/generated/core/fetcher/makePassthroughRequest.ts
1357
+ async function makePassthroughRequest(input, init, clientOptions, requestOptions) {
1358
+ const logger = createLogger(clientOptions.logging);
1359
+ let url;
1360
+ let effectiveInit = init;
1361
+ if (input instanceof Request) {
1362
+ url = input.url;
1363
+ if (init == null) {
1364
+ effectiveInit = {
1365
+ method: input.method,
1366
+ headers: Object.fromEntries(input.headers.entries()),
1367
+ body: input.body,
1368
+ signal: input.signal,
1369
+ credentials: input.credentials,
1370
+ cache: input.cache,
1371
+ redirect: input.redirect,
1372
+ referrer: input.referrer,
1373
+ integrity: input.integrity,
1374
+ mode: input.mode
1375
+ };
1376
+ }
1377
+ } else {
1378
+ url = input instanceof URL ? input.toString() : input;
1379
+ }
1380
+ const baseUrl = (clientOptions.baseUrl != null ? await Supplier.get(clientOptions.baseUrl) : void 0) ?? (clientOptions.environment != null ? await Supplier.get(clientOptions.environment) : void 0);
1381
+ let fullUrl;
1382
+ if (url.startsWith("http://") || url.startsWith("https://")) {
1383
+ fullUrl = url;
1384
+ } else if (baseUrl != null) {
1385
+ fullUrl = join(baseUrl, url);
1386
+ } else {
1387
+ fullUrl = url;
1388
+ }
1389
+ const mergedHeaders = {};
1390
+ if (clientOptions.headers != null) {
1391
+ for (const [key, value] of Object.entries(clientOptions.headers)) {
1392
+ const resolved = await EndpointSupplier.get(value, { endpointMetadata: {} });
1393
+ if (resolved != null) {
1394
+ mergedHeaders[key.toLowerCase()] = `${resolved}`;
1395
+ }
1396
+ }
1397
+ }
1398
+ if (clientOptions.getAuthHeaders != null) {
1399
+ const authHeaders = await clientOptions.getAuthHeaders();
1400
+ for (const [key, value] of Object.entries(authHeaders)) {
1401
+ mergedHeaders[key.toLowerCase()] = value;
1402
+ }
1403
+ }
1404
+ if (effectiveInit?.headers != null) {
1405
+ const initHeaders = effectiveInit.headers instanceof Headers ? Object.fromEntries(effectiveInit.headers.entries()) : Array.isArray(effectiveInit.headers) ? Object.fromEntries(effectiveInit.headers) : effectiveInit.headers;
1406
+ for (const [key, value] of Object.entries(initHeaders)) {
1407
+ if (value != null) {
1408
+ mergedHeaders[key.toLowerCase()] = value;
1409
+ }
1410
+ }
1411
+ }
1412
+ if (requestOptions?.headers != null) {
1413
+ for (const [key, value] of Object.entries(requestOptions.headers)) {
1414
+ mergedHeaders[key.toLowerCase()] = value;
1415
+ }
1416
+ }
1417
+ const method = effectiveInit?.method ?? "GET";
1418
+ const body = effectiveInit?.body;
1419
+ const timeoutInSeconds = requestOptions?.timeoutInSeconds ?? clientOptions.timeoutInSeconds;
1420
+ const timeoutMs = timeoutInSeconds != null ? timeoutInSeconds * 1e3 : void 0;
1421
+ const maxRetries = requestOptions?.maxRetries ?? clientOptions.maxRetries;
1422
+ const abortSignal = requestOptions?.abortSignal ?? effectiveInit?.signal ?? void 0;
1423
+ const fetchFn = clientOptions.fetch ?? await getFetchFn();
1424
+ if (logger.isDebug()) {
1425
+ logger.debug("Making passthrough HTTP request", {
1426
+ method,
1427
+ url: fullUrl,
1428
+ hasBody: body != null
1429
+ });
1430
+ }
1431
+ const response = await requestWithRetries(
1432
+ async () => makeRequest(
1433
+ fetchFn,
1434
+ fullUrl,
1435
+ method,
1436
+ mergedHeaders,
1437
+ body ?? void 0,
1438
+ timeoutMs,
1439
+ abortSignal,
1440
+ effectiveInit?.credentials === "include",
1441
+ void 0,
1442
+ // duplex
1443
+ false
1444
+ // disableCache
1445
+ ),
1446
+ maxRetries
1447
+ );
1448
+ if (logger.isDebug()) {
1449
+ logger.debug("Passthrough HTTP request completed", {
1450
+ method,
1451
+ url: fullUrl,
1452
+ statusCode: response.status
1453
+ });
1454
+ }
1455
+ return response;
1456
+ }
1457
+
1458
+ // ../../packages/client/src/generated/core/logging/index.ts
1459
+ var logging_exports = {};
1460
+ __export(logging_exports, {
1461
+ ConsoleLogger: () => ConsoleLogger,
1462
+ LogLevel: () => LogLevel,
1463
+ Logger: () => Logger,
1464
+ createLogger: () => createLogger
1465
+ });
1466
+
1467
+ // ../../packages/client/src/generated/core/runtime/runtime.ts
1468
+ var RUNTIME = evaluateRuntime();
1469
+ function evaluateRuntime() {
1470
+ const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
1471
+ if (isBrowser) {
1472
+ return {
1473
+ type: "browser",
1474
+ version: window.navigator.userAgent
1475
+ };
1476
+ }
1477
+ const isCloudflare = typeof globalThis !== "undefined" && globalThis?.navigator?.userAgent === "Cloudflare-Workers";
1478
+ if (isCloudflare) {
1479
+ return {
1480
+ type: "workerd"
1481
+ };
1482
+ }
1483
+ const isEdgeRuntime = typeof EdgeRuntime === "string";
1484
+ if (isEdgeRuntime) {
1485
+ return {
1486
+ type: "edge-runtime"
1487
+ };
1488
+ }
1489
+ const isWebWorker = typeof self === "object" && typeof self?.importScripts === "function" && (self.constructor?.name === "DedicatedWorkerGlobalScope" || self.constructor?.name === "ServiceWorkerGlobalScope" || self.constructor?.name === "SharedWorkerGlobalScope");
1490
+ if (isWebWorker) {
1491
+ return {
1492
+ type: "web-worker"
1493
+ };
1494
+ }
1495
+ const isDeno = typeof Deno !== "undefined" && typeof Deno.version !== "undefined" && typeof Deno.version.deno !== "undefined";
1496
+ if (isDeno) {
1497
+ return {
1498
+ type: "deno",
1499
+ version: Deno.version.deno
1500
+ };
1501
+ }
1502
+ const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
1503
+ if (isBun) {
1504
+ return {
1505
+ type: "bun",
1506
+ version: Bun.version
1507
+ };
1508
+ }
1509
+ const isReactNative = typeof navigator !== "undefined" && navigator?.product === "ReactNative";
1510
+ if (isReactNative) {
1511
+ return {
1512
+ type: "react-native"
1513
+ };
1514
+ }
1515
+ const _process = typeof process !== "undefined" ? process : void 0;
1516
+ const isNode = typeof _process !== "undefined" && typeof _process.versions?.node === "string";
1517
+ if (isNode) {
1518
+ return {
1519
+ type: "node",
1520
+ version: _process.versions.node,
1521
+ parsedVersion: Number(_process.versions.node.split(".")[0])
1522
+ };
1523
+ }
1524
+ return {
1525
+ type: "unknown"
1526
+ };
1527
+ }
1528
+
1529
+ // ../../packages/client/src/generated/core/stream/Stream.ts
1530
+ var DATA_PREFIX = "data:";
1531
+ var EVENT_PREFIX = "event:";
1532
+ var Stream = class {
1533
+ stream;
1534
+ parse;
1535
+ /**
1536
+ * The prefix to use for each message. For example,
1537
+ * for SSE, the prefix is "data: ".
1538
+ */
1539
+ prefix;
1540
+ messageTerminator;
1541
+ streamTerminator;
1542
+ eventDiscriminator;
1543
+ controller = new AbortController();
1544
+ decoder;
1545
+ constructor({ stream, parse, eventShape, signal }) {
1546
+ this.stream = stream;
1547
+ this.parse = parse;
1548
+ if (eventShape.type === "sse") {
1549
+ this.prefix = DATA_PREFIX;
1550
+ this.messageTerminator = "\n";
1551
+ this.streamTerminator = eventShape.streamTerminator;
1552
+ this.eventDiscriminator = eventShape.eventDiscriminator;
1553
+ } else {
1554
+ this.messageTerminator = eventShape.messageTerminator;
1555
+ }
1556
+ signal?.addEventListener("abort", () => this.controller.abort());
1557
+ if (typeof TextDecoder !== "undefined") {
1558
+ this.decoder = new TextDecoder("utf-8");
1559
+ }
1560
+ }
1561
+ async *iterMessages() {
1562
+ if (this.eventDiscriminator != null) {
1563
+ yield* this.iterSseEvents();
1564
+ } else {
1565
+ yield* this.iterDataMessages();
1566
+ }
1567
+ }
1568
+ async *iterDataMessages() {
1569
+ const stream = readableStreamAsyncIterable(this.stream);
1570
+ let buf = "";
1571
+ let prefixSeen = false;
1572
+ for await (const chunk of stream) {
1573
+ buf += this.decodeChunk(chunk);
1574
+ let terminatorIndex;
1575
+ while ((terminatorIndex = buf.indexOf(this.messageTerminator)) >= 0) {
1576
+ let line = buf.slice(0, terminatorIndex);
1577
+ buf = buf.slice(terminatorIndex + this.messageTerminator.length);
1578
+ if (!line.trim()) {
1579
+ continue;
1580
+ }
1581
+ if (!prefixSeen && this.prefix != null) {
1582
+ const prefixIndex = line.indexOf(this.prefix);
1583
+ if (prefixIndex === -1) {
1584
+ continue;
1585
+ }
1586
+ prefixSeen = true;
1587
+ line = line.slice(prefixIndex + this.prefix.length);
1588
+ }
1589
+ if (this.streamTerminator != null && line.includes(this.streamTerminator)) {
1590
+ return;
1591
+ }
1592
+ const message = await this.parse(fromJson(line));
1593
+ yield message;
1594
+ prefixSeen = false;
1595
+ }
1596
+ }
1597
+ }
1598
+ async *iterSseEvents() {
1599
+ const stream = readableStreamAsyncIterable(this.stream);
1600
+ let buf = "";
1601
+ let eventType;
1602
+ let dataValue;
1603
+ for await (const chunk of stream) {
1604
+ buf += this.decodeChunk(chunk);
1605
+ let terminatorIndex;
1606
+ while ((terminatorIndex = buf.indexOf("\n")) >= 0) {
1607
+ const line = buf.slice(0, terminatorIndex).replace(/\r$/, "");
1608
+ buf = buf.slice(terminatorIndex + 1);
1609
+ if (!line.trim()) {
1610
+ if (dataValue != null) {
1611
+ const message = await this.dispatchSseEvent(dataValue, eventType);
1612
+ if (message == null) {
1613
+ return;
1614
+ }
1615
+ yield message;
1616
+ }
1617
+ eventType = void 0;
1618
+ dataValue = void 0;
1619
+ continue;
1620
+ }
1621
+ if (line.startsWith(EVENT_PREFIX)) {
1622
+ eventType = line.slice(EVENT_PREFIX.length).trim();
1623
+ } else if (line.startsWith(DATA_PREFIX)) {
1624
+ const val = line.slice(DATA_PREFIX.length).trim();
1625
+ dataValue = dataValue != null ? `${dataValue}
1626
+ ${val}` : val;
1627
+ }
1628
+ }
1629
+ }
1630
+ if (dataValue != null) {
1631
+ const message = await this.dispatchSseEvent(dataValue, eventType);
1632
+ if (message != null) {
1633
+ yield message;
1634
+ }
1635
+ }
1636
+ }
1637
+ /**
1638
+ * Parses and returns a single SSE event, or returns null if the event is a stream terminator.
1639
+ */
1640
+ async dispatchSseEvent(dataValue, eventType) {
1641
+ if (this.streamTerminator != null && dataValue.includes(this.streamTerminator)) {
1642
+ return null;
1643
+ }
1644
+ return this.parse(this.injectDiscriminator(fromJson(dataValue), eventType));
1645
+ }
1646
+ injectDiscriminator(parsed, eventType) {
1647
+ if (this.eventDiscriminator == null || eventType == null) {
1648
+ return parsed;
1649
+ }
1650
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
1651
+ return parsed;
1652
+ }
1653
+ const obj = parsed;
1654
+ if (this.eventDiscriminator in obj) {
1655
+ return parsed;
1656
+ }
1657
+ return { [this.eventDiscriminator]: eventType, ...obj };
1658
+ }
1659
+ async *[Symbol.asyncIterator]() {
1660
+ for await (const message of this.iterMessages()) {
1661
+ yield message;
1662
+ }
1663
+ }
1664
+ decodeChunk(chunk) {
1665
+ let decoded = "";
1666
+ if (this.decoder != null) {
1667
+ decoded += this.decoder.decode(chunk, { stream: true });
1668
+ } else if (RUNTIME.type === "node" && typeof chunk !== "undefined") {
1669
+ decoded += Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1670
+ }
1671
+ return decoded;
1672
+ }
1673
+ };
1674
+ function readableStreamAsyncIterable(stream) {
1675
+ if (stream[Symbol.asyncIterator]) {
1676
+ return stream;
1677
+ }
1678
+ const reader = stream.getReader();
1679
+ return {
1680
+ async next() {
1681
+ try {
1682
+ const result = await reader.read();
1683
+ if (result?.done) {
1684
+ reader.releaseLock();
1685
+ }
1686
+ return result;
1687
+ } catch (e) {
1688
+ reader.releaseLock();
1689
+ throw e;
1690
+ }
1691
+ },
1692
+ async return() {
1693
+ const cancelPromise = reader.cancel();
1694
+ reader.releaseLock();
1695
+ await cancelPromise;
1696
+ return { done: true, value: void 0 };
1697
+ },
1698
+ [Symbol.asyncIterator]() {
1699
+ return this;
1700
+ }
1701
+ };
1702
+ }
1703
+
1704
+ // ../../packages/client/src/generated/core/url/index.ts
1705
+ var url_exports = {};
1706
+ __export(url_exports, {
1707
+ encodePathParam: () => encodePathParam,
1708
+ join: () => join,
1709
+ queryBuilder: () => queryBuilder,
1710
+ toQueryString: () => toQueryString
1711
+ });
1712
+
1713
+ // ../../packages/client/src/generated/core/url/encodePathParam.ts
1714
+ function encodePathParam(param) {
1715
+ if (param === null) {
1716
+ return "null";
1717
+ }
1718
+ const typeofParam = typeof param;
1719
+ switch (typeofParam) {
1720
+ case "undefined":
1721
+ return "undefined";
1722
+ case "string":
1723
+ case "number":
1724
+ case "boolean":
1725
+ break;
1726
+ default:
1727
+ param = String(param);
1728
+ break;
1729
+ }
1730
+ return encodeURIComponent(param);
1731
+ }
1732
+
1733
+ // ../../packages/client/src/generated/core/url/QueryStringBuilder.ts
1734
+ function queryBuilder() {
1735
+ return new QueryStringBuilder();
1736
+ }
1737
+ var QueryStringBuilder = class {
1738
+ parts = /* @__PURE__ */ new Map();
1739
+ /**
1740
+ * Adds a query parameter, serializing it immediately.
1741
+ *
1742
+ * By default arrays use "repeat" format (`key=a&key=b`).
1743
+ * Pass `{ style: "comma" }` for OpenAPI `explode: false` parameters
1744
+ * to get comma-separated values (`key=a,b,c`).
1745
+ *
1746
+ * Null / undefined values are silently skipped.
1747
+ */
1748
+ add(key, value, options) {
1749
+ if (value === void 0 || value === null) {
1750
+ return this;
1751
+ }
1752
+ const serialized = toQueryString(
1753
+ { [key]: value },
1754
+ { arrayFormat: options?.style === "comma" ? "comma" : "repeat" }
1755
+ );
1756
+ if (serialized.length > 0) {
1757
+ this.parts.set(key, serialized);
1758
+ }
1759
+ return this;
1760
+ }
1761
+ /**
1762
+ * Adds multiple query parameters at once from a record.
1763
+ * All parameters use the default "repeat" array format.
1764
+ * Null / undefined values are silently skipped.
1765
+ */
1766
+ addMany(params) {
1767
+ if (params != null) {
1768
+ for (const [key, value] of Object.entries(params)) {
1769
+ this.add(key, value);
1770
+ }
1771
+ }
1772
+ return this;
1773
+ }
1774
+ /**
1775
+ * Merges additional query parameters supplied at call-time via
1776
+ * `requestOptions.queryParams`. Overrides existing keys (last-write-wins).
1777
+ */
1778
+ mergeAdditional(additionalParams) {
1779
+ if (additionalParams != null) {
1780
+ for (const [key, value] of Object.entries(additionalParams)) {
1781
+ if (value === void 0 || value === null) {
1782
+ continue;
1783
+ }
1784
+ const serialized = toQueryString({ [key]: value }, { arrayFormat: "repeat" });
1785
+ if (serialized.length > 0) {
1786
+ this.parts.set(key, serialized);
1787
+ }
1788
+ }
1789
+ }
1790
+ return this;
1791
+ }
1792
+ /**
1793
+ * Returns the assembled query string (without the leading `?`).
1794
+ * Returns an empty string when no parameters were added.
1795
+ */
1796
+ build() {
1797
+ return [...this.parts.values()].join("&");
1798
+ }
1799
+ };
1800
+
1801
+ // ../../packages/client/src/generated/BaseClient.ts
1802
+ function normalizeClientOptions(options) {
1803
+ const headers = mergeHeaders(
1804
+ {
1805
+ "X-Fern-Language": "JavaScript",
1806
+ "X-Fern-Runtime": RUNTIME.type,
1807
+ "X-Fern-Runtime-Version": RUNTIME.version
1808
+ },
1809
+ options?.headers
1810
+ );
1811
+ return {
1812
+ ...options,
1813
+ logging: logging_exports.createLogger(options?.logging),
1814
+ headers
1815
+ };
1816
+ }
1817
+
1818
+ // ../../packages/client/src/generated/environments.ts
1819
+ var CngApiEnvironment = {
1820
+ Default: "https://curly.ng"
1821
+ };
1822
+
1823
+ // ../../packages/client/src/generated/errors/handleNonStatusCodeError.ts
1824
+ function handleNonStatusCodeError(error, rawResponse, method, path6) {
1825
+ switch (error.reason) {
1826
+ case "non-json":
1827
+ throw new CngApiError({
1828
+ statusCode: error.statusCode,
1829
+ body: error.rawBody,
1830
+ rawResponse
1831
+ });
1832
+ case "body-is-null":
1833
+ throw new CngApiError({
1834
+ statusCode: error.statusCode,
1835
+ rawResponse
1836
+ });
1837
+ case "timeout":
1838
+ throw new CngApiTimeoutError(`Timeout exceeded when calling ${method} ${path6}.`, {
1839
+ cause: error.cause
1840
+ });
1841
+ case "unknown":
1842
+ throw new CngApiError({
1843
+ message: error.errorMessage,
1844
+ rawResponse,
1845
+ cause: error.cause
1846
+ });
1847
+ default:
1848
+ throw new CngApiError({
1849
+ message: "Unknown error",
1850
+ rawResponse
1851
+ });
1852
+ }
1853
+ }
1854
+
1855
+ // ../../packages/client/src/generated/api/resources/auth/client/Client.ts
1856
+ var AuthClient = class {
1857
+ _options;
1858
+ constructor(options = {}) {
1859
+ this._options = normalizeClientOptions(options);
1860
+ }
1861
+ /**
1862
+ * @param {AuthClient.RequestOptions} requestOptions - Request-specific configuration.
1863
+ *
1864
+ * @throws {@link CngApi.UnauthorizedError}
1865
+ *
1866
+ * @example
1867
+ * await client.auth.getAuthWhoami()
1868
+ */
1869
+ getAuthWhoami(requestOptions) {
1870
+ return HttpResponsePromise.fromPromise(this.__getAuthWhoami(requestOptions));
1871
+ }
1872
+ async __getAuthWhoami(requestOptions) {
1873
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
1874
+ const _response = await fetcher({
1875
+ url: url_exports.join(
1876
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
1877
+ "api/auth/whoami"
1878
+ ),
1879
+ method: "GET",
1880
+ headers: _headers,
1881
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
1882
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
1883
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
1884
+ abortSignal: requestOptions?.abortSignal,
1885
+ fetchFn: this._options?.fetch,
1886
+ logging: this._options.logging
1887
+ });
1888
+ if (_response.ok) {
1889
+ return { data: _response.body, rawResponse: _response.rawResponse };
1890
+ }
1891
+ if (_response.error.reason === "status-code") {
1892
+ switch (_response.error.statusCode) {
1893
+ case 401:
1894
+ throw new UnauthorizedError(_response.error.body, _response.rawResponse);
1895
+ default:
1896
+ throw new CngApiError({
1897
+ statusCode: _response.error.statusCode,
1898
+ body: _response.error.body,
1899
+ rawResponse: _response.rawResponse
1900
+ });
1901
+ }
1902
+ }
1903
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/auth/whoami");
1904
+ }
1905
+ };
1906
+
1907
+ // ../../packages/client/src/generated/api/resources/harnessFilesystem/client/Client.ts
1908
+ var HarnessFilesystemClient = class {
1909
+ _options;
1910
+ constructor(options = {}) {
1911
+ this._options = normalizeClientOptions(options);
1912
+ }
1913
+ /**
1914
+ * @param {CngApi.GetHarnessFilesystemReadRequest} request
1915
+ * @param {HarnessFilesystemClient.RequestOptions} requestOptions - Request-specific configuration.
1916
+ *
1917
+ * @throws {@link CngApi.BadRequestError}
1918
+ * @throws {@link CngApi.NotFoundError}
1919
+ * @throws {@link CngApi.ContentTooLargeError}
1920
+ *
1921
+ * @example
1922
+ * await client.harnessFilesystem.getHarnessFilesystemRead({
1923
+ * file_path: "file_path"
1924
+ * })
1925
+ */
1926
+ getHarnessFilesystemRead(request, requestOptions) {
1927
+ return HttpResponsePromise.fromPromise(this.__getHarnessFilesystemRead(request, requestOptions));
1928
+ }
1929
+ async __getHarnessFilesystemRead(request, requestOptions) {
1930
+ const { file_path: filePath, offset, limit } = request;
1931
+ const _queryParams = {
1932
+ file_path: filePath,
1933
+ offset,
1934
+ limit
1935
+ };
1936
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
1937
+ const _response = await fetcher({
1938
+ url: url_exports.join(
1939
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
1940
+ "api/harness/filesystem/read"
1941
+ ),
1942
+ method: "GET",
1943
+ headers: _headers,
1944
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
1945
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
1946
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
1947
+ abortSignal: requestOptions?.abortSignal,
1948
+ fetchFn: this._options?.fetch,
1949
+ logging: this._options.logging
1950
+ });
1951
+ if (_response.ok) {
1952
+ return { data: _response.body, rawResponse: _response.rawResponse };
1953
+ }
1954
+ if (_response.error.reason === "status-code") {
1955
+ switch (_response.error.statusCode) {
1956
+ case 400:
1957
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
1958
+ case 404:
1959
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
1960
+ case 413:
1961
+ throw new ContentTooLargeError(
1962
+ _response.error.body,
1963
+ _response.rawResponse
1964
+ );
1965
+ default:
1966
+ throw new CngApiError({
1967
+ statusCode: _response.error.statusCode,
1968
+ body: _response.error.body,
1969
+ rawResponse: _response.rawResponse
1970
+ });
1971
+ }
1972
+ }
1973
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/harness/filesystem/read");
1974
+ }
1975
+ /**
1976
+ * @param {CngApi.GetHarnessFilesystemGrepRequest} request
1977
+ * @param {HarnessFilesystemClient.RequestOptions} requestOptions - Request-specific configuration.
1978
+ *
1979
+ * @throws {@link CngApi.BadRequestError}
1980
+ *
1981
+ * @example
1982
+ * await client.harnessFilesystem.getHarnessFilesystemGrep({
1983
+ * pattern: "pattern"
1984
+ * })
1985
+ */
1986
+ getHarnessFilesystemGrep(request, requestOptions) {
1987
+ return HttpResponsePromise.fromPromise(this.__getHarnessFilesystemGrep(request, requestOptions));
1988
+ }
1989
+ async __getHarnessFilesystemGrep(request, requestOptions) {
1990
+ const { pattern, path: path6, include, output_mode: outputMode, context, case_insensitive: caseInsensitive } = request;
1991
+ const _queryParams = {
1992
+ pattern,
1993
+ path: path6,
1994
+ include,
1995
+ output_mode: outputMode != null ? outputMode : void 0,
1996
+ context,
1997
+ case_insensitive: Array.isArray(caseInsensitive) ? caseInsensitive.map((item) => typeof item === "string" ? item : toJson(item)) : caseInsensitive != null ? typeof caseInsensitive === "string" ? caseInsensitive : toJson(caseInsensitive) : void 0
1998
+ };
1999
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2000
+ const _response = await fetcher({
2001
+ url: url_exports.join(
2002
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2003
+ "api/harness/filesystem/grep"
2004
+ ),
2005
+ method: "GET",
2006
+ headers: _headers,
2007
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2008
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2009
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2010
+ abortSignal: requestOptions?.abortSignal,
2011
+ fetchFn: this._options?.fetch,
2012
+ logging: this._options.logging
2013
+ });
2014
+ if (_response.ok) {
2015
+ return { data: _response.body, rawResponse: _response.rawResponse };
2016
+ }
2017
+ if (_response.error.reason === "status-code") {
2018
+ switch (_response.error.statusCode) {
2019
+ case 400:
2020
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
2021
+ default:
2022
+ throw new CngApiError({
2023
+ statusCode: _response.error.statusCode,
2024
+ body: _response.error.body,
2025
+ rawResponse: _response.rawResponse
2026
+ });
2027
+ }
2028
+ }
2029
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/harness/filesystem/grep");
2030
+ }
2031
+ /**
2032
+ * @param {CngApi.GetHarnessFilesystemGlobRequest} request
2033
+ * @param {HarnessFilesystemClient.RequestOptions} requestOptions - Request-specific configuration.
2034
+ *
2035
+ * @throws {@link CngApi.BadRequestError}
2036
+ *
2037
+ * @example
2038
+ * await client.harnessFilesystem.getHarnessFilesystemGlob({
2039
+ * pattern: "pattern"
2040
+ * })
2041
+ */
2042
+ getHarnessFilesystemGlob(request, requestOptions) {
2043
+ return HttpResponsePromise.fromPromise(this.__getHarnessFilesystemGlob(request, requestOptions));
2044
+ }
2045
+ async __getHarnessFilesystemGlob(request, requestOptions) {
2046
+ const { pattern, path: path6 } = request;
2047
+ const _queryParams = {
2048
+ pattern,
2049
+ path: path6
2050
+ };
2051
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2052
+ const _response = await fetcher({
2053
+ url: url_exports.join(
2054
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2055
+ "api/harness/filesystem/glob"
2056
+ ),
2057
+ method: "GET",
2058
+ headers: _headers,
2059
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2060
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2061
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2062
+ abortSignal: requestOptions?.abortSignal,
2063
+ fetchFn: this._options?.fetch,
2064
+ logging: this._options.logging
2065
+ });
2066
+ if (_response.ok) {
2067
+ return { data: _response.body, rawResponse: _response.rawResponse };
2068
+ }
2069
+ if (_response.error.reason === "status-code") {
2070
+ switch (_response.error.statusCode) {
2071
+ case 400:
2072
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
2073
+ default:
2074
+ throw new CngApiError({
2075
+ statusCode: _response.error.statusCode,
2076
+ body: _response.error.body,
2077
+ rawResponse: _response.rawResponse
2078
+ });
2079
+ }
2080
+ }
2081
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/harness/filesystem/glob");
2082
+ }
2083
+ };
2084
+
2085
+ // ../../packages/client/src/generated/api/resources/harnessInternalKnowledges/client/Client.ts
2086
+ var HarnessInternalKnowledgesClient = class {
2087
+ _options;
2088
+ constructor(options = {}) {
2089
+ this._options = normalizeClientOptions(options);
2090
+ }
2091
+ /**
2092
+ * @param {HarnessInternalKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2093
+ *
2094
+ * @throws {@link CngApi.UnauthorizedError}
2095
+ * @throws {@link CngApi.ServiceUnavailableError}
2096
+ *
2097
+ * @example
2098
+ * await client.harnessInternalKnowledges.createHarnessSubskillAssetsSyncPlan()
2099
+ */
2100
+ createHarnessSubskillAssetsSyncPlan(requestOptions) {
2101
+ return HttpResponsePromise.fromPromise(this.__createHarnessSubskillAssetsSyncPlan(requestOptions));
2102
+ }
2103
+ async __createHarnessSubskillAssetsSyncPlan(requestOptions) {
2104
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2105
+ const _response = await fetcher({
2106
+ url: url_exports.join(
2107
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2108
+ "api/harness/internal/knowledges/sync-plans"
2109
+ ),
2110
+ method: "POST",
2111
+ headers: _headers,
2112
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2113
+ responseType: "text",
2114
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2115
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2116
+ abortSignal: requestOptions?.abortSignal,
2117
+ fetchFn: this._options?.fetch,
2118
+ logging: this._options.logging
2119
+ });
2120
+ if (_response.ok) {
2121
+ return { data: _response.body, rawResponse: _response.rawResponse };
2122
+ }
2123
+ if (_response.error.reason === "status-code") {
2124
+ switch (_response.error.statusCode) {
2125
+ case 401:
2126
+ throw new UnauthorizedError(_response.error.body, _response.rawResponse);
2127
+ case 503:
2128
+ throw new ServiceUnavailableError(_response.error.body, _response.rawResponse);
2129
+ default:
2130
+ throw new CngApiError({
2131
+ statusCode: _response.error.statusCode,
2132
+ body: _response.error.body,
2133
+ rawResponse: _response.rawResponse
2134
+ });
2135
+ }
2136
+ }
2137
+ return handleNonStatusCodeError(
2138
+ _response.error,
2139
+ _response.rawResponse,
2140
+ "POST",
2141
+ "/api/harness/internal/knowledges/sync-plans"
2142
+ );
2143
+ }
2144
+ /**
2145
+ * @param {CngApi.GetHarnessSubskillAssetRawFileRequest} request
2146
+ * @param {HarnessInternalKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2147
+ *
2148
+ * @throws {@link CngApi.UnauthorizedError}
2149
+ * @throws {@link CngApi.NotFoundError}
2150
+ * @throws {@link CngApi.ServiceUnavailableError}
2151
+ *
2152
+ * @example
2153
+ * await client.harnessInternalKnowledges.getHarnessSubskillAssetRawFile({
2154
+ * path: "x",
2155
+ * sha256: "sha256"
2156
+ * })
2157
+ */
2158
+ getHarnessSubskillAssetRawFile(request, requestOptions) {
2159
+ return HttpResponsePromise.fromPromise(this.__getHarnessSubskillAssetRawFile(request, requestOptions));
2160
+ }
2161
+ async __getHarnessSubskillAssetRawFile(request, requestOptions) {
2162
+ const { path: path6, sha256 } = request;
2163
+ const _queryParams = {
2164
+ path: path6,
2165
+ sha256
2166
+ };
2167
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2168
+ const _response = await fetcher({
2169
+ url: url_exports.join(
2170
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2171
+ "api/harness/internal/knowledges/files/raw"
2172
+ ),
2173
+ method: "GET",
2174
+ headers: _headers,
2175
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2176
+ responseType: "text",
2177
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2178
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2179
+ abortSignal: requestOptions?.abortSignal,
2180
+ fetchFn: this._options?.fetch,
2181
+ logging: this._options.logging
2182
+ });
2183
+ if (_response.ok) {
2184
+ return { data: _response.body, rawResponse: _response.rawResponse };
2185
+ }
2186
+ if (_response.error.reason === "status-code") {
2187
+ switch (_response.error.statusCode) {
2188
+ case 401:
2189
+ throw new UnauthorizedError(_response.error.body, _response.rawResponse);
2190
+ case 404:
2191
+ throw new NotFoundError(_response.error.body, _response.rawResponse);
2192
+ case 503:
2193
+ throw new ServiceUnavailableError(_response.error.body, _response.rawResponse);
2194
+ default:
2195
+ throw new CngApiError({
2196
+ statusCode: _response.error.statusCode,
2197
+ body: _response.error.body,
2198
+ rawResponse: _response.rawResponse
2199
+ });
2200
+ }
2201
+ }
2202
+ return handleNonStatusCodeError(
2203
+ _response.error,
2204
+ _response.rawResponse,
2205
+ "GET",
2206
+ "/api/harness/internal/knowledges/files/raw"
2207
+ );
2208
+ }
2209
+ /**
2210
+ * @param {HarnessInternalKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2211
+ *
2212
+ * @throws {@link CngApi.UnauthorizedError}
2213
+ *
2214
+ * @example
2215
+ * await client.harnessInternalKnowledges.listHarnessSubskillAssetHashes()
2216
+ */
2217
+ listHarnessSubskillAssetHashes(requestOptions) {
2218
+ return HttpResponsePromise.fromPromise(this.__listHarnessSubskillAssetHashes(requestOptions));
2219
+ }
2220
+ async __listHarnessSubskillAssetHashes(requestOptions) {
2221
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2222
+ const _response = await fetcher({
2223
+ url: url_exports.join(
2224
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2225
+ "api/harness/internal/knowledges/files/hashes"
2226
+ ),
2227
+ method: "GET",
2228
+ headers: _headers,
2229
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2230
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2231
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2232
+ abortSignal: requestOptions?.abortSignal,
2233
+ fetchFn: this._options?.fetch,
2234
+ logging: this._options.logging
2235
+ });
2236
+ if (_response.ok) {
2237
+ return {
2238
+ data: _response.body,
2239
+ rawResponse: _response.rawResponse
2240
+ };
2241
+ }
2242
+ if (_response.error.reason === "status-code") {
2243
+ switch (_response.error.statusCode) {
2244
+ case 401:
2245
+ throw new UnauthorizedError(_response.error.body, _response.rawResponse);
2246
+ default:
2247
+ throw new CngApiError({
2248
+ statusCode: _response.error.statusCode,
2249
+ body: _response.error.body,
2250
+ rawResponse: _response.rawResponse
2251
+ });
2252
+ }
2253
+ }
2254
+ return handleNonStatusCodeError(
2255
+ _response.error,
2256
+ _response.rawResponse,
2257
+ "GET",
2258
+ "/api/harness/internal/knowledges/files/hashes"
2259
+ );
2260
+ }
2261
+ /**
2262
+ * @param {CngApi.HarnessUploadAddRequest} request
2263
+ * @param {HarnessInternalKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2264
+ *
2265
+ * @throws {@link CngApi.UnauthorizedError}
2266
+ * @throws {@link CngApi.ConflictError}
2267
+ *
2268
+ * @example
2269
+ * await client.harnessInternalKnowledges.replaceHarnessSubskillAssets({
2270
+ * uploadedAt: "uploadedAt",
2271
+ * files: [{
2272
+ * path: "path",
2273
+ * sha256: "sha256",
2274
+ * size: 1,
2275
+ * mode: "mode",
2276
+ * assetKind: "skill",
2277
+ * subskillName: "subskillName",
2278
+ * displayTitle: "displayTitle",
2279
+ * displayDescription: "displayDescription",
2280
+ * displayRating: 1,
2281
+ * bodyText: "bodyText"
2282
+ * }]
2283
+ * })
2284
+ */
2285
+ replaceHarnessSubskillAssets(request, requestOptions) {
2286
+ return HttpResponsePromise.fromPromise(this.__replaceHarnessSubskillAssets(request, requestOptions));
2287
+ }
2288
+ async __replaceHarnessSubskillAssets(request, requestOptions) {
2289
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2290
+ const _response = await fetcher({
2291
+ url: url_exports.join(
2292
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2293
+ "api/harness/internal/knowledges/files"
2294
+ ),
2295
+ method: "POST",
2296
+ headers: _headers,
2297
+ contentType: "application/json",
2298
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2299
+ requestType: "json",
2300
+ body: request,
2301
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2302
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2303
+ abortSignal: requestOptions?.abortSignal,
2304
+ fetchFn: this._options?.fetch,
2305
+ logging: this._options.logging
2306
+ });
2307
+ if (_response.ok) {
2308
+ return { data: _response.body, rawResponse: _response.rawResponse };
2309
+ }
2310
+ if (_response.error.reason === "status-code") {
2311
+ switch (_response.error.statusCode) {
2312
+ case 401:
2313
+ throw new UnauthorizedError(_response.error.body, _response.rawResponse);
2314
+ case 409:
2315
+ throw new ConflictError(
2316
+ _response.error.body,
2317
+ _response.rawResponse
2318
+ );
2319
+ default:
2320
+ throw new CngApiError({
2321
+ statusCode: _response.error.statusCode,
2322
+ body: _response.error.body,
2323
+ rawResponse: _response.rawResponse
2324
+ });
2325
+ }
2326
+ }
2327
+ return handleNonStatusCodeError(
2328
+ _response.error,
2329
+ _response.rawResponse,
2330
+ "POST",
2331
+ "/api/harness/internal/knowledges/files"
2332
+ );
2333
+ }
2334
+ /**
2335
+ * @param {CngApi.HarnessUploadRemoveRequest} request
2336
+ * @param {HarnessInternalKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2337
+ *
2338
+ * @throws {@link CngApi.UnauthorizedError}
2339
+ * @throws {@link CngApi.ConflictError}
2340
+ *
2341
+ * @example
2342
+ * await client.harnessInternalKnowledges.deleteHarnessSubskillAssets({
2343
+ * uploadedAt: "uploadedAt",
2344
+ * paths: ["paths"]
2345
+ * })
2346
+ */
2347
+ deleteHarnessSubskillAssets(request, requestOptions) {
2348
+ return HttpResponsePromise.fromPromise(this.__deleteHarnessSubskillAssets(request, requestOptions));
2349
+ }
2350
+ async __deleteHarnessSubskillAssets(request, requestOptions) {
2351
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2352
+ const _response = await fetcher({
2353
+ url: url_exports.join(
2354
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2355
+ "api/harness/internal/knowledges/files"
2356
+ ),
2357
+ method: "DELETE",
2358
+ headers: _headers,
2359
+ contentType: "application/json",
2360
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2361
+ requestType: "json",
2362
+ body: request,
2363
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2364
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2365
+ abortSignal: requestOptions?.abortSignal,
2366
+ fetchFn: this._options?.fetch,
2367
+ logging: this._options.logging
2368
+ });
2369
+ if (_response.ok) {
2370
+ return {
2371
+ data: _response.body,
2372
+ rawResponse: _response.rawResponse
2373
+ };
2374
+ }
2375
+ if (_response.error.reason === "status-code") {
2376
+ switch (_response.error.statusCode) {
2377
+ case 401:
2378
+ throw new UnauthorizedError(_response.error.body, _response.rawResponse);
2379
+ case 409:
2380
+ throw new ConflictError(
2381
+ _response.error.body,
2382
+ _response.rawResponse
2383
+ );
2384
+ default:
2385
+ throw new CngApiError({
2386
+ statusCode: _response.error.statusCode,
2387
+ body: _response.error.body,
2388
+ rawResponse: _response.rawResponse
2389
+ });
2390
+ }
2391
+ }
2392
+ return handleNonStatusCodeError(
2393
+ _response.error,
2394
+ _response.rawResponse,
2395
+ "DELETE",
2396
+ "/api/harness/internal/knowledges/files"
2397
+ );
2398
+ }
2399
+ /**
2400
+ * @param {CngApi.HarnessUploadSubskillAssetsVectorizeRequest} request
2401
+ * @param {HarnessInternalKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2402
+ *
2403
+ * @throws {@link CngApi.UnauthorizedError}
2404
+ * @throws {@link CngApi.InternalServerError}
2405
+ *
2406
+ * @example
2407
+ * await client.harnessInternalKnowledges.createHarnessSubskillAssetsIndex({
2408
+ * runId: "runId",
2409
+ * offset: 1,
2410
+ * limit: 1
2411
+ * })
2412
+ */
2413
+ createHarnessSubskillAssetsIndex(request, requestOptions) {
2414
+ return HttpResponsePromise.fromPromise(this.__createHarnessSubskillAssetsIndex(request, requestOptions));
2415
+ }
2416
+ async __createHarnessSubskillAssetsIndex(request, requestOptions) {
2417
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2418
+ const _response = await fetcher({
2419
+ url: url_exports.join(
2420
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2421
+ "api/harness/internal/knowledges/indexes"
2422
+ ),
2423
+ method: "POST",
2424
+ headers: _headers,
2425
+ contentType: "application/json",
2426
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2427
+ requestType: "json",
2428
+ body: request,
2429
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2430
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2431
+ abortSignal: requestOptions?.abortSignal,
2432
+ fetchFn: this._options?.fetch,
2433
+ logging: this._options.logging
2434
+ });
2435
+ if (_response.ok) {
2436
+ return {
2437
+ data: _response.body,
2438
+ rawResponse: _response.rawResponse
2439
+ };
2440
+ }
2441
+ if (_response.error.reason === "status-code") {
2442
+ switch (_response.error.statusCode) {
2443
+ case 401:
2444
+ throw new UnauthorizedError(_response.error.body, _response.rawResponse);
2445
+ case 500:
2446
+ throw new InternalServerError(
2447
+ _response.error.body,
2448
+ _response.rawResponse
2449
+ );
2450
+ default:
2451
+ throw new CngApiError({
2452
+ statusCode: _response.error.statusCode,
2453
+ body: _response.error.body,
2454
+ rawResponse: _response.rawResponse
2455
+ });
2456
+ }
2457
+ }
2458
+ return handleNonStatusCodeError(
2459
+ _response.error,
2460
+ _response.rawResponse,
2461
+ "POST",
2462
+ "/api/harness/internal/knowledges/indexes"
2463
+ );
2464
+ }
2465
+ };
2466
+
2467
+ // ../../packages/client/src/generated/api/resources/harnessKnowledges/client/Client.ts
2468
+ var HarnessKnowledgesClient = class {
2469
+ _options;
2470
+ constructor(options = {}) {
2471
+ this._options = normalizeClientOptions(options);
2472
+ }
2473
+ /**
2474
+ * @param {HarnessKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2475
+ *
2476
+ * @example
2477
+ * await client.harnessKnowledges.getHarnessKnowledgesCatalog()
2478
+ */
2479
+ getHarnessKnowledgesCatalog(requestOptions) {
2480
+ return HttpResponsePromise.fromPromise(this.__getHarnessKnowledgesCatalog(requestOptions));
2481
+ }
2482
+ async __getHarnessKnowledgesCatalog(requestOptions) {
2483
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2484
+ const _response = await fetcher({
2485
+ url: url_exports.join(
2486
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2487
+ "api/harness/knowledges/catalog"
2488
+ ),
2489
+ method: "GET",
2490
+ headers: _headers,
2491
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2492
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2493
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2494
+ abortSignal: requestOptions?.abortSignal,
2495
+ fetchFn: this._options?.fetch,
2496
+ logging: this._options.logging
2497
+ });
2498
+ if (_response.ok) {
2499
+ return {
2500
+ data: _response.body,
2501
+ rawResponse: _response.rawResponse
2502
+ };
2503
+ }
2504
+ if (_response.error.reason === "status-code") {
2505
+ throw new CngApiError({
2506
+ statusCode: _response.error.statusCode,
2507
+ body: _response.error.body,
2508
+ rawResponse: _response.rawResponse
2509
+ });
2510
+ }
2511
+ return handleNonStatusCodeError(
2512
+ _response.error,
2513
+ _response.rawResponse,
2514
+ "GET",
2515
+ "/api/harness/knowledges/catalog"
2516
+ );
2517
+ }
2518
+ /**
2519
+ * @param {HarnessKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2520
+ *
2521
+ * @example
2522
+ * await client.harnessKnowledges.listHarnessKnowledgesAudiences()
2523
+ */
2524
+ listHarnessKnowledgesAudiences(requestOptions) {
2525
+ return HttpResponsePromise.fromPromise(this.__listHarnessKnowledgesAudiences(requestOptions));
2526
+ }
2527
+ async __listHarnessKnowledgesAudiences(requestOptions) {
2528
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2529
+ const _response = await fetcher({
2530
+ url: url_exports.join(
2531
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2532
+ "api/harness/knowledges/audiences"
2533
+ ),
2534
+ method: "GET",
2535
+ headers: _headers,
2536
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2537
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2538
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2539
+ abortSignal: requestOptions?.abortSignal,
2540
+ fetchFn: this._options?.fetch,
2541
+ logging: this._options.logging
2542
+ });
2543
+ if (_response.ok) {
2544
+ return { data: _response.body, rawResponse: _response.rawResponse };
2545
+ }
2546
+ if (_response.error.reason === "status-code") {
2547
+ throw new CngApiError({
2548
+ statusCode: _response.error.statusCode,
2549
+ body: _response.error.body,
2550
+ rawResponse: _response.rawResponse
2551
+ });
2552
+ }
2553
+ return handleNonStatusCodeError(
2554
+ _response.error,
2555
+ _response.rawResponse,
2556
+ "GET",
2557
+ "/api/harness/knowledges/audiences"
2558
+ );
2559
+ }
2560
+ /**
2561
+ * @param {CngApi.ListHarnessSubskillAssetsRequest} request
2562
+ * @param {HarnessKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2563
+ *
2564
+ * @example
2565
+ * await client.harnessKnowledges.listHarnessSubskillAssets()
2566
+ */
2567
+ listHarnessSubskillAssets(request = {}, requestOptions) {
2568
+ return HttpResponsePromise.fromPromise(this.__listHarnessSubskillAssets(request, requestOptions));
2569
+ }
2570
+ async __listHarnessSubskillAssets(request = {}, requestOptions) {
2571
+ const { q, audience, limit } = request;
2572
+ const _queryParams = {
2573
+ q,
2574
+ audience: audience != null ? audience : void 0,
2575
+ limit
2576
+ };
2577
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2578
+ const _response = await fetcher({
2579
+ url: url_exports.join(
2580
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2581
+ "api/harness/knowledges/files"
2582
+ ),
2583
+ method: "GET",
2584
+ headers: _headers,
2585
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2586
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2587
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2588
+ abortSignal: requestOptions?.abortSignal,
2589
+ fetchFn: this._options?.fetch,
2590
+ logging: this._options.logging
2591
+ });
2592
+ if (_response.ok) {
2593
+ return {
2594
+ data: _response.body,
2595
+ rawResponse: _response.rawResponse
2596
+ };
2597
+ }
2598
+ if (_response.error.reason === "status-code") {
2599
+ throw new CngApiError({
2600
+ statusCode: _response.error.statusCode,
2601
+ body: _response.error.body,
2602
+ rawResponse: _response.rawResponse
2603
+ });
2604
+ }
2605
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/harness/knowledges/files");
2606
+ }
2607
+ /**
2608
+ * @param {CngApi.SearchHarnessKnowledgesRequest} request
2609
+ * @param {HarnessKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2610
+ *
2611
+ * @throws {@link CngApi.InternalServerError}
2612
+ *
2613
+ * @example
2614
+ * await client.harnessKnowledges.searchHarnessKnowledges({
2615
+ * q: "q"
2616
+ * })
2617
+ */
2618
+ searchHarnessKnowledges(request, requestOptions) {
2619
+ return HttpResponsePromise.fromPromise(this.__searchHarnessKnowledges(request, requestOptions));
2620
+ }
2621
+ async __searchHarnessKnowledges(request, requestOptions) {
2622
+ const { q, limit } = request;
2623
+ const _queryParams = {
2624
+ q,
2625
+ limit
2626
+ };
2627
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2628
+ const _response = await fetcher({
2629
+ url: url_exports.join(
2630
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2631
+ "api/harness/knowledges/search"
2632
+ ),
2633
+ method: "GET",
2634
+ headers: _headers,
2635
+ queryString: url_exports.queryBuilder().addMany(_queryParams).mergeAdditional(requestOptions?.queryParams).build(),
2636
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2637
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2638
+ abortSignal: requestOptions?.abortSignal,
2639
+ fetchFn: this._options?.fetch,
2640
+ logging: this._options.logging
2641
+ });
2642
+ if (_response.ok) {
2643
+ return {
2644
+ data: _response.body,
2645
+ rawResponse: _response.rawResponse
2646
+ };
2647
+ }
2648
+ if (_response.error.reason === "status-code") {
2649
+ switch (_response.error.statusCode) {
2650
+ case 500:
2651
+ throw new InternalServerError(
2652
+ _response.error.body,
2653
+ _response.rawResponse
2654
+ );
2655
+ default:
2656
+ throw new CngApiError({
2657
+ statusCode: _response.error.statusCode,
2658
+ body: _response.error.body,
2659
+ rawResponse: _response.rawResponse
2660
+ });
2661
+ }
2662
+ }
2663
+ return handleNonStatusCodeError(
2664
+ _response.error,
2665
+ _response.rawResponse,
2666
+ "GET",
2667
+ "/api/harness/knowledges/search"
2668
+ );
2669
+ }
2670
+ /**
2671
+ * @param {HarnessKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2672
+ *
2673
+ * @example
2674
+ * await client.harnessKnowledges.getHarnessKnowledgesConnectome()
2675
+ */
2676
+ getHarnessKnowledgesConnectome(requestOptions) {
2677
+ return HttpResponsePromise.fromPromise(this.__getHarnessKnowledgesConnectome(requestOptions));
2678
+ }
2679
+ async __getHarnessKnowledgesConnectome(requestOptions) {
2680
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2681
+ const _response = await fetcher({
2682
+ url: url_exports.join(
2683
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2684
+ "api/harness/knowledges/connectome"
2685
+ ),
2686
+ method: "GET",
2687
+ headers: _headers,
2688
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2689
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2690
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2691
+ abortSignal: requestOptions?.abortSignal,
2692
+ fetchFn: this._options?.fetch,
2693
+ logging: this._options.logging
2694
+ });
2695
+ if (_response.ok) {
2696
+ return { data: _response.body, rawResponse: _response.rawResponse };
2697
+ }
2698
+ if (_response.error.reason === "status-code") {
2699
+ throw new CngApiError({
2700
+ statusCode: _response.error.statusCode,
2701
+ body: _response.error.body,
2702
+ rawResponse: _response.rawResponse
2703
+ });
2704
+ }
2705
+ return handleNonStatusCodeError(
2706
+ _response.error,
2707
+ _response.rawResponse,
2708
+ "GET",
2709
+ "/api/harness/knowledges/connectome"
2710
+ );
2711
+ }
2712
+ /**
2713
+ * @param {HarnessKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2714
+ *
2715
+ * @example
2716
+ * await client.harnessKnowledges.getHarnessKnowledgesBrain()
2717
+ */
2718
+ getHarnessKnowledgesBrain(requestOptions) {
2719
+ return HttpResponsePromise.fromPromise(this.__getHarnessKnowledgesBrain(requestOptions));
2720
+ }
2721
+ async __getHarnessKnowledgesBrain(requestOptions) {
2722
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2723
+ const _response = await fetcher({
2724
+ url: url_exports.join(
2725
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2726
+ "api/harness/knowledges/brain"
2727
+ ),
2728
+ method: "GET",
2729
+ headers: _headers,
2730
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2731
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2732
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2733
+ abortSignal: requestOptions?.abortSignal,
2734
+ fetchFn: this._options?.fetch,
2735
+ logging: this._options.logging
2736
+ });
2737
+ if (_response.ok) {
2738
+ return { data: _response.body, rawResponse: _response.rawResponse };
2739
+ }
2740
+ if (_response.error.reason === "status-code") {
2741
+ throw new CngApiError({
2742
+ statusCode: _response.error.statusCode,
2743
+ body: _response.error.body,
2744
+ rawResponse: _response.rawResponse
2745
+ });
2746
+ }
2747
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/harness/knowledges/brain");
2748
+ }
2749
+ /**
2750
+ * Returns the full subskill index for agent discovery. Use search for semantic lookup, or filesystem/read for content.
2751
+ *
2752
+ * @param {HarnessKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2753
+ *
2754
+ * @example
2755
+ * await client.harnessKnowledges.listHarnessKnowledgesSubskills()
2756
+ */
2757
+ listHarnessKnowledgesSubskills(requestOptions) {
2758
+ return HttpResponsePromise.fromPromise(this.__listHarnessKnowledgesSubskills(requestOptions));
2759
+ }
2760
+ async __listHarnessKnowledgesSubskills(requestOptions) {
2761
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2762
+ const _response = await fetcher({
2763
+ url: url_exports.join(
2764
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2765
+ "api/harness/knowledges/subskills"
2766
+ ),
2767
+ method: "GET",
2768
+ headers: _headers,
2769
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2770
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2771
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2772
+ abortSignal: requestOptions?.abortSignal,
2773
+ fetchFn: this._options?.fetch,
2774
+ logging: this._options.logging
2775
+ });
2776
+ if (_response.ok) {
2777
+ return { data: _response.body, rawResponse: _response.rawResponse };
2778
+ }
2779
+ if (_response.error.reason === "status-code") {
2780
+ throw new CngApiError({
2781
+ statusCode: _response.error.statusCode,
2782
+ body: _response.error.body,
2783
+ rawResponse: _response.rawResponse
2784
+ });
2785
+ }
2786
+ return handleNonStatusCodeError(
2787
+ _response.error,
2788
+ _response.rawResponse,
2789
+ "GET",
2790
+ "/api/harness/knowledges/subskills"
2791
+ );
2792
+ }
2793
+ /**
2794
+ * @param {HarnessKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2795
+ *
2796
+ * @example
2797
+ * await client.harnessKnowledges.getHarnessKnowledgesInstallScript()
2798
+ */
2799
+ getHarnessKnowledgesInstallScript(requestOptions) {
2800
+ return HttpResponsePromise.fromPromise(this.__getHarnessKnowledgesInstallScript(requestOptions));
2801
+ }
2802
+ async __getHarnessKnowledgesInstallScript(requestOptions) {
2803
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2804
+ const _response = await fetcher({
2805
+ url: url_exports.join(
2806
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2807
+ "api/harness/knowledges/install.sh"
2808
+ ),
2809
+ method: "GET",
2810
+ headers: _headers,
2811
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2812
+ responseType: "text",
2813
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2814
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2815
+ abortSignal: requestOptions?.abortSignal,
2816
+ fetchFn: this._options?.fetch,
2817
+ logging: this._options.logging
2818
+ });
2819
+ if (_response.ok) {
2820
+ return { data: _response.body, rawResponse: _response.rawResponse };
2821
+ }
2822
+ if (_response.error.reason === "status-code") {
2823
+ throw new CngApiError({
2824
+ statusCode: _response.error.statusCode,
2825
+ body: _response.error.body,
2826
+ rawResponse: _response.rawResponse
2827
+ });
2828
+ }
2829
+ return handleNonStatusCodeError(
2830
+ _response.error,
2831
+ _response.rawResponse,
2832
+ "GET",
2833
+ "/api/harness/knowledges/install.sh"
2834
+ );
2835
+ }
2836
+ /**
2837
+ * @param {HarnessKnowledgesClient.RequestOptions} requestOptions - Request-specific configuration.
2838
+ *
2839
+ * @example
2840
+ * await client.harnessKnowledges.getHarnessKnowledgesInstallPowerShell()
2841
+ */
2842
+ getHarnessKnowledgesInstallPowerShell(requestOptions) {
2843
+ return HttpResponsePromise.fromPromise(this.__getHarnessKnowledgesInstallPowerShell(requestOptions));
2844
+ }
2845
+ async __getHarnessKnowledgesInstallPowerShell(requestOptions) {
2846
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2847
+ const _response = await fetcher({
2848
+ url: url_exports.join(
2849
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2850
+ "api/harness/knowledges/install.ps1"
2851
+ ),
2852
+ method: "GET",
2853
+ headers: _headers,
2854
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2855
+ responseType: "text",
2856
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2857
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2858
+ abortSignal: requestOptions?.abortSignal,
2859
+ fetchFn: this._options?.fetch,
2860
+ logging: this._options.logging
2861
+ });
2862
+ if (_response.ok) {
2863
+ return { data: _response.body, rawResponse: _response.rawResponse };
2864
+ }
2865
+ if (_response.error.reason === "status-code") {
2866
+ throw new CngApiError({
2867
+ statusCode: _response.error.statusCode,
2868
+ body: _response.error.body,
2869
+ rawResponse: _response.rawResponse
2870
+ });
2871
+ }
2872
+ return handleNonStatusCodeError(
2873
+ _response.error,
2874
+ _response.rawResponse,
2875
+ "GET",
2876
+ "/api/harness/knowledges/install.ps1"
2877
+ );
2878
+ }
2879
+ };
2880
+
2881
+ // ../../packages/client/src/generated/api/resources/llm/client/Client.ts
2882
+ var LlmClient = class {
2883
+ _options;
2884
+ constructor(options = {}) {
2885
+ this._options = normalizeClientOptions(options);
2886
+ }
2887
+ /**
2888
+ * @param {LlmClient.RequestOptions} requestOptions - Request-specific configuration.
2889
+ *
2890
+ * @example
2891
+ * await client.llm.getLlmHealth()
2892
+ */
2893
+ getLlmHealth(requestOptions) {
2894
+ return HttpResponsePromise.fromPromise(this.__getLlmHealth(requestOptions));
2895
+ }
2896
+ async __getLlmHealth(requestOptions) {
2897
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2898
+ const _response = await fetcher({
2899
+ url: url_exports.join(
2900
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2901
+ "api/llm/health"
2902
+ ),
2903
+ method: "GET",
2904
+ headers: _headers,
2905
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2906
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2907
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2908
+ abortSignal: requestOptions?.abortSignal,
2909
+ fetchFn: this._options?.fetch,
2910
+ logging: this._options.logging
2911
+ });
2912
+ if (_response.ok) {
2913
+ return { data: _response.body, rawResponse: _response.rawResponse };
2914
+ }
2915
+ if (_response.error.reason === "status-code") {
2916
+ throw new CngApiError({
2917
+ statusCode: _response.error.statusCode,
2918
+ body: _response.error.body,
2919
+ rawResponse: _response.rawResponse
2920
+ });
2921
+ }
2922
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/llm/health");
2923
+ }
2924
+ createLlmChat(request, requestOptions) {
2925
+ return HttpResponsePromise.fromPromise(this.__createLlmChat(request, requestOptions));
2926
+ }
2927
+ async __createLlmChat(request, requestOptions) {
2928
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2929
+ const _response = await fetcher({
2930
+ url: url_exports.join(
2931
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2932
+ "api/llm/chat"
2933
+ ),
2934
+ method: "POST",
2935
+ headers: _headers,
2936
+ contentType: "application/json",
2937
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
2938
+ requestType: "json",
2939
+ body: request,
2940
+ responseType: "sse",
2941
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
2942
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
2943
+ abortSignal: requestOptions?.abortSignal,
2944
+ fetchFn: this._options?.fetch,
2945
+ logging: this._options.logging
2946
+ });
2947
+ if (_response.ok) {
2948
+ return {
2949
+ data: new Stream({
2950
+ stream: _response.body,
2951
+ parse: (data) => data,
2952
+ signal: requestOptions?.abortSignal,
2953
+ eventShape: {
2954
+ type: "sse"
2955
+ }
2956
+ }),
2957
+ rawResponse: _response.rawResponse
2958
+ };
2959
+ }
2960
+ if (_response.error.reason === "status-code") {
2961
+ switch (_response.error.statusCode) {
2962
+ case 400:
2963
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
2964
+ default:
2965
+ throw new CngApiError({
2966
+ statusCode: _response.error.statusCode,
2967
+ body: _response.error.body,
2968
+ rawResponse: _response.rawResponse
2969
+ });
2970
+ }
2971
+ }
2972
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/api/llm/chat");
2973
+ }
2974
+ };
2975
+
2976
+ // ../../packages/client/src/generated/api/resources/polar/client/Client.ts
2977
+ var PolarClient = class {
2978
+ _options;
2979
+ constructor(options = {}) {
2980
+ this._options = normalizeClientOptions(options);
2981
+ }
2982
+ /**
2983
+ * @param {PolarClient.RequestOptions} requestOptions - Request-specific configuration.
2984
+ *
2985
+ * @throws {@link CngApi.BadGatewayError}
2986
+ * @throws {@link CngApi.ServiceUnavailableError}
2987
+ *
2988
+ * @example
2989
+ * await client.polar.createHarnessPolarCheckout()
2990
+ */
2991
+ createHarnessPolarCheckout(requestOptions) {
2992
+ return HttpResponsePromise.fromPromise(this.__createHarnessPolarCheckout(requestOptions));
2993
+ }
2994
+ async __createHarnessPolarCheckout(requestOptions) {
2995
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
2996
+ const _response = await fetcher({
2997
+ url: url_exports.join(
2998
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
2999
+ "api/polar/harness/checkout"
3000
+ ),
3001
+ method: "GET",
3002
+ headers: _headers,
3003
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
3004
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
3005
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
3006
+ abortSignal: requestOptions?.abortSignal,
3007
+ fetchFn: this._options?.fetch,
3008
+ logging: this._options.logging
3009
+ });
3010
+ if (_response.ok) {
3011
+ return { data: void 0, rawResponse: _response.rawResponse };
3012
+ }
3013
+ if (_response.error.reason === "status-code") {
3014
+ switch (_response.error.statusCode) {
3015
+ case 502:
3016
+ throw new BadGatewayError(
3017
+ _response.error.body,
3018
+ _response.rawResponse
3019
+ );
3020
+ case 503:
3021
+ throw new ServiceUnavailableError(_response.error.body, _response.rawResponse);
3022
+ default:
3023
+ throw new CngApiError({
3024
+ statusCode: _response.error.statusCode,
3025
+ body: _response.error.body,
3026
+ rawResponse: _response.rawResponse
3027
+ });
3028
+ }
3029
+ }
3030
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/polar/harness/checkout");
3031
+ }
3032
+ };
3033
+
3034
+ // ../../packages/client/src/generated/api/resources/system/client/Client.ts
3035
+ var SystemClient = class {
3036
+ _options;
3037
+ constructor(options = {}) {
3038
+ this._options = normalizeClientOptions(options);
3039
+ }
3040
+ /**
3041
+ * @param {SystemClient.RequestOptions} requestOptions - Request-specific configuration.
3042
+ *
3043
+ * @example
3044
+ * await client.system.getHealth()
3045
+ */
3046
+ getHealth(requestOptions) {
3047
+ return HttpResponsePromise.fromPromise(this.__getHealth(requestOptions));
3048
+ }
3049
+ async __getHealth(requestOptions) {
3050
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
3051
+ const _response = await fetcher({
3052
+ url: url_exports.join(
3053
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
3054
+ "api/health"
3055
+ ),
3056
+ method: "GET",
3057
+ headers: _headers,
3058
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
3059
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
3060
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
3061
+ abortSignal: requestOptions?.abortSignal,
3062
+ fetchFn: this._options?.fetch,
3063
+ logging: this._options.logging
3064
+ });
3065
+ if (_response.ok) {
3066
+ return { data: _response.body, rawResponse: _response.rawResponse };
3067
+ }
3068
+ if (_response.error.reason === "status-code") {
3069
+ throw new CngApiError({
3070
+ statusCode: _response.error.statusCode,
3071
+ body: _response.error.body,
3072
+ rawResponse: _response.rawResponse
3073
+ });
3074
+ }
3075
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/health");
3076
+ }
3077
+ };
3078
+
3079
+ // ../../packages/client/src/generated/api/resources/telemetry/client/Client.ts
3080
+ var TelemetryClient = class {
3081
+ _options;
3082
+ constructor(options = {}) {
3083
+ this._options = normalizeClientOptions(options);
3084
+ }
3085
+ /**
3086
+ * @param {CngApi.NavigationEventRequest} request
3087
+ * @param {TelemetryClient.RequestOptions} requestOptions - Request-specific configuration.
3088
+ *
3089
+ * @throws {@link CngApi.BadRequestError}
3090
+ *
3091
+ * @example
3092
+ * await client.telemetry.createNavigationEvent({
3093
+ * url: "url",
3094
+ * pathname: "pathname",
3095
+ * timestamp: "2024-01-15T09:30:00Z"
3096
+ * })
3097
+ */
3098
+ createNavigationEvent(request, requestOptions) {
3099
+ return HttpResponsePromise.fromPromise(this.__createNavigationEvent(request, requestOptions));
3100
+ }
3101
+ async __createNavigationEvent(request, requestOptions) {
3102
+ const _headers = mergeHeaders(this._options?.headers, requestOptions?.headers);
3103
+ const _response = await fetcher({
3104
+ url: url_exports.join(
3105
+ await Supplier.get(this._options.baseUrl) ?? await Supplier.get(this._options.environment) ?? CngApiEnvironment.Default,
3106
+ "api/navigation-events"
3107
+ ),
3108
+ method: "POST",
3109
+ headers: _headers,
3110
+ contentType: "application/json",
3111
+ queryString: url_exports.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),
3112
+ requestType: "json",
3113
+ body: request,
3114
+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1e3,
3115
+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,
3116
+ abortSignal: requestOptions?.abortSignal,
3117
+ fetchFn: this._options?.fetch,
3118
+ logging: this._options.logging
3119
+ });
3120
+ if (_response.ok) {
3121
+ return {
3122
+ data: _response.body,
3123
+ rawResponse: _response.rawResponse
3124
+ };
3125
+ }
3126
+ if (_response.error.reason === "status-code") {
3127
+ switch (_response.error.statusCode) {
3128
+ case 400:
3129
+ throw new BadRequestError(_response.error.body, _response.rawResponse);
3130
+ default:
3131
+ throw new CngApiError({
3132
+ statusCode: _response.error.statusCode,
3133
+ body: _response.error.body,
3134
+ rawResponse: _response.rawResponse
3135
+ });
3136
+ }
3137
+ }
3138
+ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/api/navigation-events");
3139
+ }
3140
+ };
3141
+
3142
+ // ../../packages/client/src/generated/Client.ts
3143
+ var CngApiClient = class {
3144
+ _options;
3145
+ _system;
3146
+ _auth;
3147
+ _harnessKnowledges;
3148
+ _harnessFilesystem;
3149
+ _harnessInternalKnowledges;
3150
+ _polar;
3151
+ _telemetry;
3152
+ _llm;
3153
+ constructor(options = {}) {
3154
+ this._options = normalizeClientOptions(options);
3155
+ }
3156
+ get system() {
3157
+ return this._system ??= new SystemClient(this._options);
3158
+ }
3159
+ get auth() {
3160
+ return this._auth ??= new AuthClient(this._options);
3161
+ }
3162
+ get harnessKnowledges() {
3163
+ return this._harnessKnowledges ??= new HarnessKnowledgesClient(this._options);
3164
+ }
3165
+ get harnessFilesystem() {
3166
+ return this._harnessFilesystem ??= new HarnessFilesystemClient(this._options);
3167
+ }
3168
+ get harnessInternalKnowledges() {
3169
+ return this._harnessInternalKnowledges ??= new HarnessInternalKnowledgesClient(this._options);
3170
+ }
3171
+ get polar() {
3172
+ return this._polar ??= new PolarClient(this._options);
3173
+ }
3174
+ get telemetry() {
3175
+ return this._telemetry ??= new TelemetryClient(this._options);
3176
+ }
3177
+ get llm() {
3178
+ return this._llm ??= new LlmClient(this._options);
3179
+ }
3180
+ /**
3181
+ * Make a passthrough request using the SDK's configured auth, retry, logging, etc.
3182
+ * This is useful for making requests to endpoints not yet supported in the SDK.
3183
+ * The input can be a URL string, URL object, or Request object. Relative paths are resolved against the configured base URL.
3184
+ *
3185
+ * @param {Request | string | URL} input - The URL, path, or Request object.
3186
+ * @param {RequestInit} init - Standard fetch RequestInit options.
3187
+ * @param {core.PassthroughRequest.RequestOptions} requestOptions - Per-request overrides (timeout, retries, headers, abort signal).
3188
+ * @returns {Promise<Response>} A standard Response object.
3189
+ */
3190
+ async fetch(input, init, requestOptions) {
3191
+ return makePassthroughRequest(
3192
+ input,
3193
+ init,
3194
+ {
3195
+ baseUrl: this._options.baseUrl ?? this._options.environment,
3196
+ headers: this._options.headers,
3197
+ timeoutInSeconds: this._options.timeoutInSeconds,
3198
+ maxRetries: this._options.maxRetries,
3199
+ fetch: this._options.fetch,
3200
+ logging: this._options.logging
3201
+ },
3202
+ requestOptions
3203
+ );
3204
+ }
3205
+ };
3206
+
3207
+ // ../../packages/client/src/generated/core/logging/exports.ts
3208
+ var logging;
3209
+ ((logging2) => {
3210
+ logging2.LogLevel = LogLevel;
3211
+ logging2.ConsoleLogger = ConsoleLogger;
3212
+ })(logging || (logging = {}));
3213
+
3214
+ // src/api.ts
3215
+ function createCngApiClient(options) {
3216
+ return new CngApiClient({
3217
+ baseUrl: resolveApiBaseUrl(options),
3218
+ timeoutInSeconds: 15,
3219
+ maxRetries: 1
3220
+ });
3221
+ }
3222
+ async function readBackendHealth(options) {
3223
+ try {
3224
+ const client = createCngApiClient(options);
3225
+ const health = await client.system.getHealth();
3226
+ return {
3227
+ ok: true,
3228
+ service: health.service
3229
+ };
3230
+ } catch (error) {
3231
+ return {
3232
+ ok: false,
3233
+ message: error instanceof Error ? error.message : "unknown error"
3234
+ };
3235
+ }
3236
+ }
3237
+
3238
+ // src/browser.ts
3239
+ import { spawn } from "child_process";
3240
+ import process2 from "process";
3241
+ async function openBrowserUrl(url) {
3242
+ const command = browserOpenCommand(url);
3243
+ return await new Promise((resolve, reject) => {
3244
+ const childProcess = spawn(command.command, command.args, {
3245
+ detached: true,
3246
+ stdio: "ignore"
3247
+ });
3248
+ childProcess.on("error", (error) => {
3249
+ if (error.code === "ENOENT") {
3250
+ resolve(false);
3251
+ return;
3252
+ }
3253
+ reject(error);
3254
+ });
3255
+ childProcess.on("spawn", () => {
3256
+ childProcess.unref();
3257
+ resolve(true);
3258
+ });
3259
+ });
3260
+ }
3261
+ function browserOpenCommand(url) {
3262
+ if (process2.platform === "darwin") {
3263
+ return { command: "open", args: [url] };
3264
+ }
3265
+ if (process2.platform === "win32") {
3266
+ return { command: "cmd", args: ["/c", "start", "", url] };
3267
+ }
3268
+ return { command: "xdg-open", args: [url] };
3269
+ }
3270
+
3271
+ // src/scrub/masker.ts
3272
+ import fs from "fs/promises";
3273
+ import path from "path";
3274
+ async function scrubFindingsInline(targetPath, findings) {
3275
+ const target = await resolveScrubTarget(targetPath);
3276
+ const findingsByFile = groupFindingsBySafePath(target, findings);
3277
+ let filesChanged = 0;
3278
+ let replacements = 0;
3279
+ for (const [absolutePath, fileFindings] of findingsByFile.safeFindingsByPath) {
3280
+ const originalContent = await fs.readFile(absolutePath, "utf8");
3281
+ let scrubbedContent = originalContent;
3282
+ let fileReplacements = 0;
3283
+ for (const finding of fileFindings) {
3284
+ const placeholder = formatSecretPlaceholder(finding);
3285
+ const nextContent = scrubbedContent.split(finding.rawSecret).join(placeholder);
3286
+ if (nextContent !== scrubbedContent) {
3287
+ fileReplacements += countOccurrences(scrubbedContent, finding.rawSecret);
3288
+ scrubbedContent = nextContent;
3289
+ }
3290
+ }
3291
+ if (scrubbedContent !== originalContent) {
3292
+ await fs.writeFile(absolutePath, scrubbedContent);
3293
+ filesChanged += 1;
3294
+ replacements += fileReplacements;
3295
+ }
3296
+ }
3297
+ return {
3298
+ filesChanged,
3299
+ replacements,
3300
+ skippedFindings: findingsByFile.skippedFindings
3301
+ };
3302
+ }
3303
+ function formatSecretPlaceholder(finding) {
3304
+ return `[CNGKIT_SECRET:${sanitizePlaceholderPart(finding.detectorName)}:${finding.verified ? "verified" : "unverified"}]`;
3305
+ }
3306
+ function groupFindingsBySafePath(target, findings) {
3307
+ const safeFindingsByPath = /* @__PURE__ */ new Map();
3308
+ let skippedFindings = 0;
3309
+ for (const finding of findings) {
3310
+ const absolutePath = resolveSafeFindingPath(target, finding.filePath);
3311
+ if (!absolutePath) {
3312
+ skippedFindings += 1;
3313
+ continue;
3314
+ }
3315
+ const fileFindings = safeFindingsByPath.get(absolutePath) ?? [];
3316
+ fileFindings.push(finding);
3317
+ safeFindingsByPath.set(absolutePath, fileFindings);
3318
+ }
3319
+ return { safeFindingsByPath, skippedFindings };
3320
+ }
3321
+ async function resolveScrubTarget(targetPath) {
3322
+ const absoluteTargetPath = path.resolve(targetPath);
3323
+ const stat = await fs.stat(absoluteTargetPath);
3324
+ if (stat.isFile()) {
3325
+ return {
3326
+ rootDir: path.dirname(absoluteTargetPath),
3327
+ allowedFilePath: absoluteTargetPath
3328
+ };
3329
+ }
3330
+ return {
3331
+ rootDir: absoluteTargetPath
3332
+ };
3333
+ }
3334
+ function resolveSafeFindingPath(target, findingFilePath) {
3335
+ const absolutePath = path.isAbsolute(findingFilePath) ? path.resolve(findingFilePath) : path.resolve(target.rootDir, findingFilePath);
3336
+ if (target.allowedFilePath) {
3337
+ return absolutePath === target.allowedFilePath ? absolutePath : void 0;
3338
+ }
3339
+ const normalizedRoot = `${path.resolve(target.rootDir)}${path.sep}`;
3340
+ if (absolutePath === path.resolve(target.rootDir) || absolutePath.startsWith(normalizedRoot)) {
3341
+ return absolutePath;
3342
+ }
3343
+ return void 0;
3344
+ }
3345
+ function countOccurrences(value, search) {
3346
+ if (!search) {
3347
+ return 0;
3348
+ }
3349
+ return value.split(search).length - 1;
3350
+ }
3351
+ function sanitizePlaceholderPart(value) {
3352
+ return value.replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") || "Unknown";
3353
+ }
3354
+
3355
+ // src/scrub/trufflehog.ts
3356
+ import { spawn as spawn2 } from "child_process";
3357
+ import path2 from "path";
3358
+
3359
+ // src/scrub/findings.ts
3360
+ function parseTruffleHogJsonLines(output) {
3361
+ const findings = [];
3362
+ for (const line of output.split(/\r?\n/)) {
3363
+ const trimmedLine = line.trim();
3364
+ if (!trimmedLine.startsWith("{")) {
3365
+ continue;
3366
+ }
3367
+ const parsedLine = parseJsonRecord(trimmedLine);
3368
+ if (!parsedLine) {
3369
+ continue;
3370
+ }
3371
+ const finding = parseTruffleHogFinding(parsedLine);
3372
+ if (finding) {
3373
+ findings.push(finding);
3374
+ }
3375
+ }
3376
+ return findings;
3377
+ }
3378
+ function parseTruffleHogFinding(finding) {
3379
+ const rawSecret = readString(finding.Raw) || readString(finding.RawV2);
3380
+ const filePath = readFilesystemFilePath(finding);
3381
+ if (!rawSecret || !filePath) {
3382
+ return void 0;
3383
+ }
3384
+ return {
3385
+ detectorName: readString(finding.DetectorName) || "Unknown",
3386
+ filePath,
3387
+ line: readFilesystemLine(finding),
3388
+ rawSecret,
3389
+ redactedSecret: readString(finding.Redacted) || "",
3390
+ verified: finding.Verified === true
3391
+ };
3392
+ }
3393
+ function readFilesystemFilePath(finding) {
3394
+ const filesystem = readFilesystemMetadata(finding);
3395
+ if (!filesystem) {
3396
+ return void 0;
3397
+ }
3398
+ return readString(filesystem.file) || readString(filesystem.path);
3399
+ }
3400
+ function readFilesystemLine(finding) {
3401
+ const filesystem = readFilesystemMetadata(finding);
3402
+ if (!filesystem) {
3403
+ return void 0;
3404
+ }
3405
+ return typeof filesystem.line === "number" ? filesystem.line : void 0;
3406
+ }
3407
+ function readFilesystemMetadata(finding) {
3408
+ const sourceMetadata = readRecord(finding.SourceMetadata);
3409
+ const data = readRecord(sourceMetadata?.Data);
3410
+ return readRecord(data?.Filesystem);
3411
+ }
3412
+ function parseJsonRecord(line) {
3413
+ try {
3414
+ return readRecord(JSON.parse(line));
3415
+ } catch {
3416
+ return void 0;
3417
+ }
3418
+ }
3419
+ function isJsonRecord(value) {
3420
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
3421
+ return false;
3422
+ }
3423
+ const prototype = Object.getPrototypeOf(value);
3424
+ return prototype === Object.prototype || prototype === null;
3425
+ }
3426
+ function readRecord(value) {
3427
+ return isJsonRecord(value) ? value : void 0;
3428
+ }
3429
+ function readString(value) {
3430
+ return typeof value === "string" && value.length > 0 ? value : void 0;
3431
+ }
3432
+
3433
+ // src/scrub/trufflehog.ts
3434
+ async function scanFilesystemWithTruffleHog(targetPath, options) {
3435
+ const absoluteTargetPath = path2.resolve(options.cwd, targetPath);
3436
+ const { stdout } = await runTruffleHog([
3437
+ "filesystem",
3438
+ absoluteTargetPath,
3439
+ "--json",
3440
+ "--no-update",
3441
+ "--force-skip-binaries",
3442
+ "--force-skip-archives"
3443
+ ]);
3444
+ return parseTruffleHogJsonLines(stdout);
3445
+ }
3446
+ function runTruffleHog(args) {
3447
+ return new Promise((resolve, reject) => {
3448
+ const child = spawn2("trufflehog", args, {
3449
+ stdio: ["ignore", "pipe", "pipe"]
3450
+ });
3451
+ const stdoutChunks = [];
3452
+ const stderrChunks = [];
3453
+ child.stdout.on("data", (chunk) => {
3454
+ stdoutChunks.push(chunk);
3455
+ });
3456
+ child.stderr.on("data", (chunk) => {
3457
+ stderrChunks.push(chunk);
3458
+ });
3459
+ child.on("error", (error) => {
3460
+ if (error.code === "ENOENT") {
3461
+ reject(
3462
+ new Error(
3463
+ "TruffleHog is not installed. Install it with `brew install trufflehog` or see https://github.com/trufflesecurity/trufflehog."
3464
+ )
3465
+ );
3466
+ return;
3467
+ }
3468
+ reject(error);
3469
+ });
3470
+ child.on("close", (exitCode) => {
3471
+ const stdout = Buffer.concat(stdoutChunks).toString("utf8");
3472
+ const stderr = Buffer.concat(stderrChunks).toString("utf8");
3473
+ if (exitCode && exitCode !== 0) {
3474
+ reject(new Error(`TruffleHog scan failed with exit code ${exitCode}: ${stderr.trim()}`));
3475
+ return;
3476
+ }
3477
+ resolve({ stdout, stderr });
3478
+ });
3479
+ });
3480
+ }
3481
+
3482
+ // src/sync/client.ts
3483
+ import process3 from "process";
3484
+ import chokidar from "chokidar";
3485
+ import WebSocket from "ws";
3486
+
3487
+ // src/sync/files.ts
3488
+ import fs2 from "fs/promises";
3489
+ import path4 from "path";
3490
+
3491
+ // src/sync/paths.ts
3492
+ import { execFile } from "child_process";
3493
+ import path3 from "path";
3494
+ import { promisify } from "util";
3495
+ var execFileAsync = promisify(execFile);
3496
+ async function resolveRepoContext(cwd) {
3497
+ try {
3498
+ const { stdout } = await execFileAsync("git", ["rev-parse", "--show-toplevel"], {
3499
+ cwd
3500
+ });
3501
+ return { rootDir: path3.resolve(stdout.trim()) };
3502
+ } catch {
3503
+ return { rootDir: path3.resolve(cwd) };
3504
+ }
3505
+ }
3506
+ function toRepoRelativePath(rootDir, absolutePath) {
3507
+ const relativePath = path3.relative(rootDir, absolutePath);
3508
+ if (!relativePath || relativePath.startsWith("..") || path3.isAbsolute(relativePath)) {
3509
+ return void 0;
3510
+ }
3511
+ return relativePath.split(path3.sep).join("/");
3512
+ }
3513
+ function resolveRepoPath(rootDir, relativePath) {
3514
+ if (!isSafeRelativePath(relativePath)) {
3515
+ return void 0;
3516
+ }
3517
+ const absolutePath = path3.resolve(rootDir, relativePath);
3518
+ const normalizedRoot = `${path3.resolve(rootDir)}${path3.sep}`;
3519
+ if (absolutePath !== path3.resolve(rootDir) && !absolutePath.startsWith(normalizedRoot)) {
3520
+ return void 0;
3521
+ }
3522
+ return absolutePath;
3523
+ }
3524
+ function isSafeRelativePath(relativePath) {
3525
+ if (!relativePath || relativePath.startsWith("/") || relativePath.includes("\0")) {
3526
+ return false;
3527
+ }
3528
+ const normalizedParts = relativePath.split(/[\\/]+/).filter(Boolean);
3529
+ if (normalizedParts.includes("..")) {
3530
+ return false;
3531
+ }
3532
+ return normalizedParts[0] !== ".git";
3533
+ }
3534
+ async function shouldSyncRelativePath(context, relativePath) {
3535
+ if (!isSafeRelativePath(relativePath)) {
3536
+ return false;
3537
+ }
3538
+ try {
3539
+ await execFileAsync("git", ["check-ignore", "--quiet", "--", relativePath], {
3540
+ cwd: context.rootDir
3541
+ });
3542
+ return false;
3543
+ } catch (error) {
3544
+ const exitCode = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
3545
+ return exitCode === 1;
3546
+ }
3547
+ }
3548
+
3549
+ // src/sync/files.ts
3550
+ function createSuppressionTracker(windowMs = 1500) {
3551
+ const suppressedUntilByPath = /* @__PURE__ */ new Map();
3552
+ return {
3553
+ suppress(relativePath) {
3554
+ suppressedUntilByPath.set(relativePath, Date.now() + windowMs);
3555
+ },
3556
+ isSuppressed(relativePath) {
3557
+ const suppressedUntil = suppressedUntilByPath.get(relativePath);
3558
+ if (!suppressedUntil) {
3559
+ return false;
3560
+ }
3561
+ if (suppressedUntil < Date.now()) {
3562
+ suppressedUntilByPath.delete(relativePath);
3563
+ return false;
3564
+ }
3565
+ return true;
3566
+ }
3567
+ };
3568
+ }
3569
+ async function* collectSnapshotMessages(context, peerId) {
3570
+ yield* collectDirectorySnapshot(context, context.rootDir, peerId);
3571
+ }
3572
+ async function* collectDirectorySnapshot(context, directoryPath, peerId) {
3573
+ const entries = await fs2.opendir(directoryPath);
3574
+ for await (const entry of entries) {
3575
+ const absolutePath = path4.join(directoryPath, entry.name);
3576
+ const relativePath = toRepoRelativePath(context.rootDir, absolutePath);
3577
+ if (!relativePath || !await shouldSyncRelativePath(context, relativePath)) {
3578
+ continue;
3579
+ }
3580
+ if (entry.isDirectory()) {
3581
+ yield* collectDirectorySnapshot(context, absolutePath, peerId);
3582
+ continue;
3583
+ }
3584
+ if (!entry.isFile()) {
3585
+ continue;
3586
+ }
3587
+ const [content, stat] = await Promise.all([fs2.readFile(absolutePath), fs2.stat(absolutePath)]);
3588
+ yield {
3589
+ type: "file",
3590
+ peerId,
3591
+ path: relativePath,
3592
+ contentBase64: content.toString("base64"),
3593
+ mtimeMs: stat.mtimeMs,
3594
+ sentAt: Date.now()
3595
+ };
3596
+ }
3597
+ }
3598
+ async function buildFileMessage(context, peerId, relativePath) {
3599
+ if (!await shouldSyncRelativePath(context, relativePath)) {
3600
+ return void 0;
3601
+ }
3602
+ const absolutePath = resolveRepoPath(context.rootDir, relativePath);
3603
+ if (!absolutePath) {
3604
+ return void 0;
3605
+ }
3606
+ const stat = await fs2.stat(absolutePath);
3607
+ if (!stat.isFile()) {
3608
+ return void 0;
3609
+ }
3610
+ const content = await fs2.readFile(absolutePath);
3611
+ return {
3612
+ type: "file",
3613
+ peerId,
3614
+ path: relativePath,
3615
+ contentBase64: content.toString("base64"),
3616
+ mtimeMs: stat.mtimeMs,
3617
+ sentAt: Date.now()
3618
+ };
3619
+ }
3620
+ async function applyRemoteMessage(context, message, suppressionTracker) {
3621
+ const absolutePath = resolveRepoPath(context.rootDir, message.path);
3622
+ if (!absolutePath || !await shouldSyncRelativePath(context, message.path)) {
3623
+ return;
3624
+ }
3625
+ suppressionTracker.suppress(message.path);
3626
+ if (message.type === "delete") {
3627
+ await fs2.rm(absolutePath, { force: true });
3628
+ return;
3629
+ }
3630
+ await fs2.mkdir(path4.dirname(absolutePath), { recursive: true });
3631
+ await fs2.writeFile(absolutePath, Buffer.from(message.contentBase64, "base64"));
3632
+ }
3633
+
3634
+ // src/sync/protocol.ts
3635
+ import { z } from "zod";
3636
+ var SyncBaseMessageSchema = z.object({
3637
+ peerId: z.string().min(1),
3638
+ sentAt: z.number().finite()
3639
+ });
3640
+ var SyncHelloMessageSchema = SyncBaseMessageSchema.extend({
3641
+ type: z.literal("hello"),
3642
+ role: z.union([z.literal("share"), z.literal("join")])
3643
+ });
3644
+ var SyncFileMessageSchema = SyncBaseMessageSchema.extend({
3645
+ type: z.literal("file"),
3646
+ path: z.string().min(1),
3647
+ contentBase64: z.string(),
3648
+ mtimeMs: z.number().finite()
3649
+ });
3650
+ var SyncDeleteMessageSchema = SyncBaseMessageSchema.extend({
3651
+ type: z.literal("delete"),
3652
+ path: z.string().min(1),
3653
+ mtimeMs: z.number().finite()
3654
+ });
3655
+ var SyncSnapshotCompleteMessageSchema = SyncBaseMessageSchema.extend({
3656
+ type: z.literal("snapshot-complete"),
3657
+ fileCount: z.number().int().nonnegative()
3658
+ });
3659
+ var SyncMessageSchema = z.discriminatedUnion("type", [
3660
+ SyncHelloMessageSchema,
3661
+ SyncFileMessageSchema,
3662
+ SyncDeleteMessageSchema,
3663
+ SyncSnapshotCompleteMessageSchema
3664
+ ]);
3665
+ function encodeSyncMessage(message) {
3666
+ return JSON.stringify(SyncMessageSchema.parse(message));
3667
+ }
3668
+ function decodeSyncMessage(value) {
3669
+ if (typeof value !== "string") {
3670
+ return void 0;
3671
+ }
3672
+ try {
3673
+ return SyncMessageSchema.parse(JSON.parse(value));
3674
+ } catch {
3675
+ return void 0;
3676
+ }
3677
+ }
3678
+
3679
+ // src/sync/client.ts
3680
+ function createSyncWebSocketUrl(apiBaseUrl, roomCode) {
3681
+ const url = new URL(apiBaseUrl);
3682
+ url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
3683
+ url.pathname = `/api/cng/sync/${encodeURIComponent(roomCode)}`;
3684
+ url.search = "";
3685
+ url.hash = "";
3686
+ return url.toString();
3687
+ }
3688
+ function sendMessage(socket, message) {
3689
+ if (socket.readyState === WebSocket.OPEN) {
3690
+ socket.send(encodeSyncMessage(message));
3691
+ }
3692
+ }
3693
+ async function startSyncSession(options) {
3694
+ const repoContext = await resolveRepoContext(options.cwd);
3695
+ const peerId = createPeerId();
3696
+ const suppressionTracker = createSuppressionTracker();
3697
+ const webSocketUrl = createSyncWebSocketUrl(options.apiBaseUrl, options.roomCode);
3698
+ const socket = new WebSocket(webSocketUrl);
3699
+ options.output.info(`Room: ${options.roomCode}`);
3700
+ options.output.info(`Repo: ${repoContext.rootDir}`);
3701
+ options.output.info(`Peer: ${peerId}`);
3702
+ const watcherContext = {
3703
+ repoContext,
3704
+ socket,
3705
+ peerId,
3706
+ suppressionTracker,
3707
+ output: options.output
3708
+ };
3709
+ const watcher = createRepoWatcher(watcherContext);
3710
+ socket.on("open", () => {
3711
+ sendMessage(socket, {
3712
+ type: "hello",
3713
+ peerId,
3714
+ role: options.role,
3715
+ sentAt: Date.now()
3716
+ });
3717
+ void sendInitialSnapshot(socket, repoContext, peerId, options.output);
3718
+ });
3719
+ socket.on("message", (data) => {
3720
+ void handleRemoteMessage({
3721
+ data,
3722
+ repoContext,
3723
+ peerId,
3724
+ suppressionTracker,
3725
+ output: options.output
3726
+ });
3727
+ });
3728
+ await waitForSessionClose(socket, watcher);
3729
+ }
3730
+ function createRepoWatcher(context) {
3731
+ const watcher = chokidar.watch(context.repoContext.rootDir, {
3732
+ ignoreInitial: true,
3733
+ ignored: (candidatePath) => {
3734
+ const relativePath = toRepoRelativePath(context.repoContext.rootDir, candidatePath);
3735
+ return relativePath?.split("/").includes(".git") ?? false;
3736
+ }
3737
+ });
3738
+ watcher.on("add", (absolutePath) => {
3739
+ void sendLocalFileChange(context, absolutePath);
3740
+ });
3741
+ watcher.on("change", (absolutePath) => {
3742
+ void sendLocalFileChange(context, absolutePath);
3743
+ });
3744
+ watcher.on("unlink", (absolutePath) => {
3745
+ void sendLocalDelete(context, absolutePath);
3746
+ });
3747
+ return watcher;
3748
+ }
3749
+ async function sendInitialSnapshot(socket, repoContext, peerId, output) {
3750
+ let fileCount = 0;
3751
+ for await (const message of collectSnapshotMessages(repoContext, peerId)) {
3752
+ sendMessage(socket, message);
3753
+ fileCount += 1;
3754
+ }
3755
+ sendMessage(socket, {
3756
+ type: "snapshot-complete",
3757
+ peerId,
3758
+ sentAt: Date.now(),
3759
+ fileCount
3760
+ });
3761
+ output.info(`sent snapshot ${fileCount} files`);
3762
+ }
3763
+ async function sendLocalFileChange(context, absolutePath) {
3764
+ const relativePath = toRepoRelativePath(context.repoContext.rootDir, absolutePath);
3765
+ if (!relativePath || context.suppressionTracker.isSuppressed(relativePath)) {
3766
+ return;
3767
+ }
3768
+ const message = await buildFileMessage(context.repoContext, context.peerId, relativePath);
3769
+ if (!message) {
3770
+ return;
3771
+ }
3772
+ sendMessage(context.socket, message);
3773
+ context.output.info(`sent file ${relativePath}`);
3774
+ }
3775
+ async function sendLocalDelete(context, absolutePath) {
3776
+ const relativePath = toRepoRelativePath(context.repoContext.rootDir, absolutePath);
3777
+ if (!relativePath || context.suppressionTracker.isSuppressed(relativePath)) {
3778
+ return;
3779
+ }
3780
+ if (!await shouldSyncRelativePath(context.repoContext, relativePath)) {
3781
+ return;
3782
+ }
3783
+ sendMessage(context.socket, {
3784
+ type: "delete",
3785
+ peerId: context.peerId,
3786
+ path: relativePath,
3787
+ mtimeMs: Date.now(),
3788
+ sentAt: Date.now()
3789
+ });
3790
+ context.output.info(`sent delete ${relativePath}`);
3791
+ }
3792
+ async function handleRemoteMessage(options) {
3793
+ const decodedMessage = decodeSyncMessage(options.data.toString());
3794
+ if (!decodedMessage || decodedMessage.peerId === options.peerId) {
3795
+ return;
3796
+ }
3797
+ if (decodedMessage.type === "hello") {
3798
+ options.output.info(`peer joined ${decodedMessage.peerId}`);
3799
+ return;
3800
+ }
3801
+ if (decodedMessage.type === "snapshot-complete") {
3802
+ options.output.info(`peer snapshot complete ${decodedMessage.fileCount} files`);
3803
+ return;
3804
+ }
3805
+ await applyRemoteMessage(options.repoContext, decodedMessage, options.suppressionTracker);
3806
+ options.output.info(`applied ${decodedMessage.type} ${decodedMessage.path}`);
3807
+ }
3808
+ async function waitForSessionClose(socket, watcher) {
3809
+ await new Promise((resolve, reject) => {
3810
+ let settled = false;
3811
+ const closeSession = async () => {
3812
+ await watcher.close();
3813
+ if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {
3814
+ socket.close();
3815
+ }
3816
+ };
3817
+ const finish = async () => {
3818
+ if (settled) {
3819
+ return;
3820
+ }
3821
+ settled = true;
3822
+ process3.off("SIGINT", onSignal);
3823
+ process3.off("SIGTERM", onSignal);
3824
+ await closeSession();
3825
+ resolve();
3826
+ };
3827
+ const onSignal = () => {
3828
+ void finish();
3829
+ };
3830
+ socket.on("error", async (error) => {
3831
+ if (settled) {
3832
+ return;
3833
+ }
3834
+ settled = true;
3835
+ process3.off("SIGINT", onSignal);
3836
+ process3.off("SIGTERM", onSignal);
3837
+ await closeSession();
3838
+ reject(error);
3839
+ });
3840
+ socket.on("close", () => {
3841
+ void finish();
3842
+ });
3843
+ process3.on("SIGINT", onSignal);
3844
+ process3.on("SIGTERM", onSignal);
3845
+ });
3846
+ }
3847
+
3848
+ // src/transcripts/reader.ts
3849
+ import { promises as fs3 } from "fs";
3850
+ import os from "os";
3851
+ import path5 from "path";
3852
+ var TranscriptSourceNames = ["codex", "claude"];
3853
+ async function listTranscriptRecords(options) {
3854
+ const files = await discoverTranscriptFiles(options.source);
3855
+ const records = await Promise.all(files.slice(0, options.limit).map(readTranscriptRecord));
3856
+ return records;
3857
+ }
3858
+ async function readTranscriptEntries(options) {
3859
+ const file = await resolveTranscriptFile(options.source, options.target);
3860
+ const entries = await readEntriesFromFile(file, options.includeInternal);
3861
+ return entries.slice(Math.max(0, entries.length - options.limit));
3862
+ }
3863
+ async function grepTranscriptEntries(options) {
3864
+ const files = await discoverTranscriptFiles(options.source);
3865
+ const normalizedQuery = options.query.toLowerCase();
3866
+ const matches = [];
3867
+ for (const file of files.slice(0, options.fileLimit)) {
3868
+ const entries = await readEntriesFromFile(file, options.includeInternal);
3869
+ for (const entry of entries) {
3870
+ if (entry.text.toLowerCase().includes(normalizedQuery)) {
3871
+ matches.push(entry);
3872
+ }
3873
+ if (matches.length >= options.limit) {
3874
+ return matches;
3875
+ }
3876
+ }
3877
+ }
3878
+ return matches;
3879
+ }
3880
+ async function discoverTranscriptFiles(source) {
3881
+ const sources = source === "all" ? TranscriptSourceNames : [source];
3882
+ const records = await Promise.all(sources.flatMap((sourceName) => sourceRoots(sourceName)));
3883
+ return records.flat().sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
3884
+ }
3885
+ function sourceRoots(source) {
3886
+ if (source === "codex") {
3887
+ return [
3888
+ discoverJsonlFiles("codex", expandHome("~/.codex/sessions")),
3889
+ discoverJsonlFiles("codex", expandHome("~/.codex/archived_sessions"))
3890
+ ];
3891
+ }
3892
+ return [
3893
+ discoverJsonlFiles("claude", expandHome("~/.claude/projects")),
3894
+ discoverJsonlFiles("claude", expandHome("~/.claude/history.jsonl"))
3895
+ ];
3896
+ }
3897
+ async function discoverJsonlFiles(source, rootPath) {
3898
+ const stat = await statIfExists(rootPath);
3899
+ if (!stat) {
3900
+ return [];
3901
+ }
3902
+ if (stat.isFile()) {
3903
+ return [await recordFromPath(source, rootPath, stat.mtime)];
3904
+ }
3905
+ const records = [];
3906
+ const entries = await fs3.readdir(rootPath, { withFileTypes: true });
3907
+ for (const entry of entries) {
3908
+ const entryPath = path5.join(rootPath, entry.name);
3909
+ if (entry.isDirectory()) {
3910
+ records.push(...await discoverJsonlFiles(source, entryPath));
3911
+ continue;
3912
+ }
3913
+ if (entry.isFile() && entry.name.endsWith(".jsonl")) {
3914
+ const entryStat = await fs3.stat(entryPath);
3915
+ records.push(await recordFromPath(source, entryPath, entryStat.mtime));
3916
+ }
3917
+ }
3918
+ return records;
3919
+ }
3920
+ async function recordFromPath(source, filePath, mtime) {
3921
+ return {
3922
+ source,
3923
+ filePath,
3924
+ updatedAt: mtime.toISOString()
3925
+ };
3926
+ }
3927
+ async function readTranscriptRecord(record) {
3928
+ const metadata = await readMetadataFromFile(record.source, record.filePath);
3929
+ return {
3930
+ ...record,
3931
+ ...metadata
3932
+ };
3933
+ }
3934
+ async function readMetadataFromFile(source, filePath) {
3935
+ const lines = await readJsonlLines(filePath, 80);
3936
+ for (const line of lines) {
3937
+ const parsed = parseJsonObject(line);
3938
+ if (!parsed) {
3939
+ continue;
3940
+ }
3941
+ if (source === "codex") {
3942
+ const payload = asObject(parsed.payload);
3943
+ if (parsed.type === "session_meta" && payload) {
3944
+ return {
3945
+ cwd: readString2(payload.cwd),
3946
+ sessionId: readString2(payload.session_id) ?? readString2(payload.id),
3947
+ title: readString2(payload.cwd)
3948
+ };
3949
+ }
3950
+ }
3951
+ if (source === "claude") {
3952
+ const message = asObject(parsed.message);
3953
+ const role = readString2(message?.role) ?? readString2(parsed.type);
3954
+ const content = message ? extractContentText(message.content) : readString2(parsed.content);
3955
+ if (content && (role === "user" || role === "assistant")) {
3956
+ return {
3957
+ cwd: readString2(parsed.cwd) ?? readString2(parsed.project),
3958
+ sessionId: readString2(parsed.sessionId),
3959
+ title: truncateSingleLine(content, 120)
3960
+ };
3961
+ }
3962
+ }
3963
+ }
3964
+ return {
3965
+ sessionId: path5.basename(filePath, ".jsonl")
3966
+ };
3967
+ }
3968
+ async function resolveTranscriptFile(source, target) {
3969
+ const expandedTarget = expandHome(target);
3970
+ const directStat = await statIfExists(expandedTarget);
3971
+ if (directStat?.isFile()) {
3972
+ return recordFromPath(detectSourceFromPath(expandedTarget), expandedTarget, directStat.mtime);
3973
+ }
3974
+ const files = await discoverTranscriptFiles(source);
3975
+ const normalizedTarget = target.toLowerCase();
3976
+ const match = files.find((file) => {
3977
+ return file.filePath.toLowerCase().includes(normalizedTarget) || file.sessionId?.toLowerCase().includes(normalizedTarget);
3978
+ });
3979
+ if (!match) {
3980
+ throw new Error(`No transcript matched "${target}". Run cngkit transcripts list first.`);
3981
+ }
3982
+ return match;
3983
+ }
3984
+ async function readEntriesFromFile(record, includeInternal) {
3985
+ const content = await fs3.readFile(record.filePath, "utf8");
3986
+ const entries = [];
3987
+ for (const line of content.split("\n")) {
3988
+ if (!line.trim()) {
3989
+ continue;
3990
+ }
3991
+ const parsed = parseJsonObject(line);
3992
+ if (!parsed) {
3993
+ continue;
3994
+ }
3995
+ const entry = record.source === "codex" ? parseCodexEntry(record, parsed, includeInternal) : parseClaudeEntry(record, parsed, includeInternal);
3996
+ if (entry) {
3997
+ entries.push(entry);
3998
+ }
3999
+ }
4000
+ return entries;
4001
+ }
4002
+ function parseCodexEntry(record, parsed, includeInternal) {
4003
+ const payload = asObject(parsed.payload);
4004
+ if (!payload || parsed.type !== "response_item") {
4005
+ return void 0;
4006
+ }
4007
+ const role = readString2(payload.role);
4008
+ if (!role || !includeInternal && role !== "user" && role !== "assistant") {
4009
+ return void 0;
4010
+ }
4011
+ const text = extractContentText(payload.content);
4012
+ if (!text) {
4013
+ return void 0;
4014
+ }
4015
+ return {
4016
+ source: record.source,
4017
+ filePath: record.filePath,
4018
+ timestamp: readString2(parsed.timestamp),
4019
+ role,
4020
+ text
4021
+ };
4022
+ }
4023
+ function parseClaudeEntry(record, parsed, includeInternal) {
4024
+ const message = asObject(parsed.message);
4025
+ const role = readString2(message?.role) ?? readString2(parsed.type);
4026
+ if (!role || !includeInternal && role !== "user" && role !== "assistant") {
4027
+ return void 0;
4028
+ }
4029
+ const text = message ? extractContentText(message.content) : readString2(parsed.content);
4030
+ if (!text) {
4031
+ return void 0;
4032
+ }
4033
+ return {
4034
+ source: record.source,
4035
+ filePath: record.filePath,
4036
+ timestamp: readString2(parsed.timestamp),
4037
+ role,
4038
+ text
4039
+ };
4040
+ }
4041
+ function extractContentText(value) {
4042
+ if (typeof value === "string") {
4043
+ return value;
4044
+ }
4045
+ if (!Array.isArray(value)) {
4046
+ return void 0;
4047
+ }
4048
+ const parts = value.flatMap((item) => {
4049
+ if (typeof item === "string") {
4050
+ return [item];
4051
+ }
4052
+ const objectItem = asObject(item);
4053
+ if (!objectItem) {
4054
+ return [];
4055
+ }
4056
+ return [readString2(objectItem.text), readString2(objectItem.content)].filter(
4057
+ (part) => Boolean(part)
4058
+ );
4059
+ });
4060
+ return parts.length > 0 ? parts.join("\n") : void 0;
4061
+ }
4062
+ async function readJsonlLines(filePath, limit) {
4063
+ const content = await fs3.readFile(filePath, "utf8");
4064
+ return content.split("\n").filter(Boolean).slice(0, limit);
4065
+ }
4066
+ async function statIfExists(filePath) {
4067
+ try {
4068
+ return await fs3.stat(filePath);
4069
+ } catch (error) {
4070
+ if (isNodeError(error) && error.code === "ENOENT") {
4071
+ return void 0;
4072
+ }
4073
+ throw error;
4074
+ }
4075
+ }
4076
+ function parseJsonObject(line) {
4077
+ try {
4078
+ const parsed = JSON.parse(line);
4079
+ return asObject(parsed);
4080
+ } catch {
4081
+ return void 0;
4082
+ }
4083
+ }
4084
+ function asObject(value) {
4085
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4086
+ return value;
4087
+ }
4088
+ return void 0;
4089
+ }
4090
+ function readString2(value) {
4091
+ return typeof value === "string" && value.trim() ? value : void 0;
4092
+ }
4093
+ function isNodeError(error) {
4094
+ return error instanceof Error && "code" in error;
4095
+ }
4096
+ function expandHome(value) {
4097
+ if (value === "~") {
4098
+ return os.homedir();
4099
+ }
4100
+ if (value.startsWith("~/")) {
4101
+ return path5.join(os.homedir(), value.slice(2));
4102
+ }
4103
+ return value;
4104
+ }
4105
+ function detectSourceFromPath(filePath) {
4106
+ return filePath.includes(`${path5.sep}.claude${path5.sep}`) ? "claude" : "codex";
4107
+ }
4108
+ function truncateSingleLine(value, maxLength) {
4109
+ const line = value.replace(/\s+/g, " ").trim();
4110
+ return line.length > maxLength ? `${line.slice(0, maxLength - 1)}...` : line;
4111
+ }
4112
+
4113
+ // src/command-actions.ts
4114
+ async function runLoginCommand(options, output) {
4115
+ const loginUrl = new URL("/login", resolveApiBaseUrl(options));
4116
+ const loginUrlString = loginUrl.toString();
4117
+ output.info(`Opening ${loginUrlString}`);
4118
+ const didOpenBrowser = await openBrowserUrl(loginUrlString);
4119
+ if (!didOpenBrowser) {
4120
+ output.info(`No browser opener found. Open this URL manually: ${loginUrlString}`);
4121
+ }
4122
+ }
4123
+ async function runShareCommand(roomCode, options, output) {
4124
+ const syncRoomCode = roomCode ?? createRoomCode();
4125
+ output.info(`Share code: ${syncRoomCode}`);
4126
+ await printBackendStatus(options, output);
4127
+ await runSyncSession("share", syncRoomCode, options, output);
4128
+ }
4129
+ async function runJoinCommand(roomCode, options, output) {
4130
+ if (!roomCode) {
4131
+ throw new Error("Missing room code. Usage: cngkit coderoom join <room-code>");
4132
+ }
4133
+ await printBackendStatus(options, output);
4134
+ await runSyncSession("join", roomCode, options, output);
4135
+ }
4136
+ async function runScrubCommand(targetPath, options, output, dependencies) {
4137
+ const scrubTargetPath = targetPath ?? ".";
4138
+ const scanFilesystem = dependencies?.scanFilesystem ?? ((scanTargetPath) => scanFilesystemWithTruffleHog(scanTargetPath, {
4139
+ cwd: process4.cwd()
4140
+ }));
4141
+ const findings = await scanFilesystem(scrubTargetPath);
4142
+ if (findings.length === 0) {
4143
+ output.info("No secrets found.");
4144
+ return;
4145
+ }
4146
+ output.info(formatScrubReport(findings));
4147
+ if (!options.yes) {
4148
+ if (options.mask) {
4149
+ throw new Error("Inline scrubbing rewrites files. Re-run with --yes to continue.");
4150
+ }
4151
+ output.info("Report only. Re-run with --yes to scrub files inline.");
4152
+ return;
4153
+ }
4154
+ const result = await scrubFindingsInline(scrubTargetPath, findings);
4155
+ output.info(
4156
+ `Masked ${result.replacements} secret${result.replacements === 1 ? "" : "s"} in ${result.filesChanged} file${result.filesChanged === 1 ? "" : "s"}.`
4157
+ );
4158
+ if (result.skippedFindings > 0) {
4159
+ output.info(`Skipped ${result.skippedFindings} finding(s) outside the scrub root.`);
4160
+ }
4161
+ }
4162
+ async function runTranscriptCommand(args, options, output) {
4163
+ const [action = "list", ...actionArgs] = args ?? [];
4164
+ const source = normalizeTranscriptSource(options.source);
4165
+ const limit = coerceLimit(options.limit, action === "list" ? 12 : 80, 500);
4166
+ const includeInternal = options.includeInternal === true;
4167
+ switch (action) {
4168
+ case "help":
4169
+ output.info(formatCngkitHelp("transcripts"));
4170
+ return;
4171
+ case "list": {
4172
+ const records = await listTranscriptRecords({ source, limit });
4173
+ if (options.json) {
4174
+ output.info(formatJson({ records }));
4175
+ return;
4176
+ }
4177
+ output.info(formatTranscriptRecords(records));
4178
+ return;
4179
+ }
4180
+ case "read": {
4181
+ const target = actionArgs[0];
4182
+ if (!target) {
4183
+ throw new Error("Missing transcript target. Usage: cngkit transcripts read <path-or-id>");
4184
+ }
4185
+ const entries = await readTranscriptEntries({
4186
+ source,
4187
+ target,
4188
+ limit,
4189
+ includeInternal
4190
+ });
4191
+ if (options.json) {
4192
+ output.info(formatJson({ entries }));
4193
+ return;
4194
+ }
4195
+ output.info(formatTranscriptEntries(entries));
4196
+ return;
4197
+ }
4198
+ case "grep": {
4199
+ const query = optionalJoinedArgument(actionArgs);
4200
+ if (!query) {
4201
+ throw new Error("Missing query. Usage: cngkit transcripts grep <query>");
4202
+ }
4203
+ const entries = await grepTranscriptEntries({
4204
+ source,
4205
+ query,
4206
+ limit,
4207
+ fileLimit: coerceLimit(options.fileLimit, 60, 5e3),
4208
+ includeInternal
4209
+ });
4210
+ if (options.json) {
4211
+ output.info(formatJson({ entries }));
4212
+ return;
4213
+ }
4214
+ output.info(formatTranscriptEntries(entries));
4215
+ return;
4216
+ }
4217
+ default:
4218
+ throw new Error("Unknown transcripts command. Usage: cngkit transcripts <list|read|grep>");
4219
+ }
4220
+ }
4221
+ async function runKnowStatusCommand(options, output, dependencies) {
4222
+ const api = dependencies?.api ?? createKnowledgesApi(options);
4223
+ const response = await api.getCatalog();
4224
+ if (options.json) {
4225
+ output.info(formatJson(response.data));
4226
+ return;
4227
+ }
4228
+ const latestRun = response.data.latestRun;
4229
+ const lines = [
4230
+ `Catalog: ${response.data.name}`,
4231
+ `Files: ${response.data.files}`,
4232
+ `Blobs: ${response.data.blobs}`,
4233
+ `Vectorize: ${response.data.vectorize.index} (${response.data.vectorize.binding})`
4234
+ ];
4235
+ if (latestRun) {
4236
+ lines.push(`Latest run: ${latestRun.status} (${latestRun.id})`);
4237
+ if (latestRun.updated_at) {
4238
+ lines.push(`Updated: ${latestRun.updated_at}`);
4239
+ }
4240
+ } else {
4241
+ lines.push("Latest run: none");
4242
+ }
4243
+ output.info(lines.join("\n"));
4244
+ }
4245
+ async function runKnowAudiencesCommand(options, output, dependencies) {
4246
+ const api = dependencies?.api ?? createKnowledgesApi(options);
4247
+ const response = await api.listAudiences();
4248
+ if (options.json) {
4249
+ output.info(formatJson(response.data));
4250
+ return;
4251
+ }
4252
+ const lines = response.data.audiences.flatMap((audience) => [
4253
+ `${audience.id} - ${audience.label}`,
4254
+ ` ${singleLine(audience.help)}`
4255
+ ]);
4256
+ output.info(lines.length > 0 ? lines.join("\n") : "No audiences available.");
4257
+ }
4258
+ async function runKnowSearchCommand(query, options, output, dependencies) {
4259
+ if (!query) {
4260
+ throw new Error("Missing search query. Usage: cngkit knowledges search <query>");
4261
+ }
4262
+ const api = dependencies?.api ?? createKnowledgesApi(options);
4263
+ const response = await api.search(query, coerceLimit(options.limit, 5));
4264
+ if (options.json) {
4265
+ output.info(formatJson(response.data));
4266
+ return;
4267
+ }
4268
+ const lines = response.data.results.flatMap((result, index) => [
4269
+ `${index + 1}. ${result.title} (${result.subskillName})`,
4270
+ ` score ${result.score.toFixed(3)} | ${result.path}`,
4271
+ ` ${singleLine(result.description || result.contentPreview)}`
4272
+ ]);
4273
+ output.info(lines.length > 0 ? lines.join("\n") : `No results for "${query}".`);
4274
+ }
4275
+ async function runKnowListCommand(query, options, output, dependencies) {
4276
+ const api = dependencies?.api ?? createKnowledgesApi(options);
4277
+ const response = await api.listSubskills();
4278
+ const limit = coerceLimit(options.limit, 25);
4279
+ const normalizedQuery = query?.toLowerCase();
4280
+ const subskills = response.data.subskills.filter((subskill) => {
4281
+ if (!normalizedQuery) {
4282
+ return true;
4283
+ }
4284
+ return [subskill.name, subskill.title, subskill.description, subskill.type].join(" ").toLowerCase().includes(normalizedQuery);
4285
+ }).slice(0, limit);
4286
+ if (options.json) {
4287
+ output.info(formatJson({ subskills, total: subskills.length }));
4288
+ return;
4289
+ }
4290
+ const lines = subskills.flatMap((subskill) => [
4291
+ `${subskill.name} [${subskill.type}]`,
4292
+ ` ${subskill.title} | files ${subskill.fileCount} | rating ${subskill.rating}`,
4293
+ ` ${singleLine(subskill.description)}`
4294
+ ]);
4295
+ output.info(lines.length > 0 ? lines.join("\n") : "No matching subskills.");
4296
+ }
4297
+ async function runKnowFilesCommand(query, options, output, dependencies) {
4298
+ const api = dependencies?.api ?? createKnowledgesApi(options);
4299
+ const response = await api.listFiles({
4300
+ query,
4301
+ audience: normalizeAudienceId(options.audience),
4302
+ limit: coerceLimit(options.limit, 25)
4303
+ });
4304
+ if (options.json) {
4305
+ output.info(formatJson(response.data));
4306
+ return;
4307
+ }
4308
+ const lines = response.data.files.map((file) => {
4309
+ const title = file.display_title ?? file.title ?? file.subskill_name ?? "Untitled";
4310
+ return `${file.path}
4311
+ ${title}`;
4312
+ });
4313
+ output.info(lines.length > 0 ? lines.join("\n") : "No matching files.");
4314
+ }
4315
+ async function runKnowReadCommand(filePath, options, output, dependencies) {
4316
+ if (!filePath) {
4317
+ throw new Error("Missing file_path. Usage: cngkit knowledges read <file_path>");
4318
+ }
4319
+ const api = dependencies?.api ?? createKnowledgesApi(options);
4320
+ const response = await api.read({
4321
+ filePath: normalizeCatalogPath(filePath),
4322
+ offset: coerceOptionalNumber(options.offset),
4323
+ limit: coerceLimit(options.limit, 200, 2e3)
4324
+ });
4325
+ if (options.json) {
4326
+ output.info(formatJson(response.data));
4327
+ return;
4328
+ }
4329
+ output.info(response.data.content);
4330
+ if (response.data.truncated) {
4331
+ output.info(
4332
+ `[truncated: showing ${response.data.limit} lines from offset ${response.data.offset} of ${response.data.total_lines}]`
4333
+ );
4334
+ }
4335
+ }
4336
+ async function runKnowGrepCommand(pattern, options, output, dependencies) {
4337
+ if (!pattern) {
4338
+ throw new Error("Missing pattern. Usage: cngkit knowledges grep <pattern>");
4339
+ }
4340
+ const api = dependencies?.api ?? createKnowledgesApi(options);
4341
+ const limit = options.limit !== void 0 ? coerceOptionalNumber(options.limit) : void 0;
4342
+ const response = await api.grep({
4343
+ pattern,
4344
+ path: normalizeCatalogPath(options.path ?? "/"),
4345
+ include: options.include ?? "*",
4346
+ mode: normalizeGrepMode(options.outputMode),
4347
+ context: coerceLimit(options.context, 0, 20),
4348
+ ignoreCase: options.caseInsensitive === true
4349
+ });
4350
+ if (options.json) {
4351
+ output.info(formatJson(response.data));
4352
+ return;
4353
+ }
4354
+ if (response.data.mode === "files_with_matches") {
4355
+ const files = limit ? response.data.files.slice(0, limit) : response.data.files;
4356
+ output.info(
4357
+ files.length > 0 ? files.join("\n") : `No files matched "${pattern}".`
4358
+ );
4359
+ return;
4360
+ }
4361
+ if (response.data.mode === "count") {
4362
+ const counts = limit ? response.data.counts.slice(0, limit) : response.data.counts;
4363
+ const lines2 = counts.map((count) => `${count.file_path}: ${count.match_count}`);
4364
+ output.info(lines2.length > 0 ? lines2.join("\n") : `No matches for "${pattern}".`);
4365
+ return;
4366
+ }
4367
+ const matches = limit ? response.data.matches.slice(0, limit) : response.data.matches;
4368
+ const lines = matches.flatMap((match) => [
4369
+ `${match.file_path}:${match.line_number}`,
4370
+ ...match.context_before.map((line) => ` ${line}`),
4371
+ `> ${match.line}`,
4372
+ ...match.context_after.map((line) => ` ${line}`)
4373
+ ]);
4374
+ output.info(lines.length > 0 ? lines.join("\n") : `No matches for "${pattern}".`);
4375
+ }
4376
+ async function runKnowGlobCommand(pattern, options, output, dependencies) {
4377
+ const api = dependencies?.api ?? createKnowledgesApi(options);
4378
+ const limit = options.limit !== void 0 ? coerceOptionalNumber(options.limit) : void 0;
4379
+ const response = await api.glob({
4380
+ pattern: pattern ?? "**/*.md",
4381
+ path: normalizeCatalogPath(options.path ?? "/")
4382
+ });
4383
+ if (options.json) {
4384
+ output.info(formatJson(response.data));
4385
+ return;
4386
+ }
4387
+ const files = limit ? response.data.files.slice(0, limit) : response.data.files;
4388
+ const wasClientTruncated = limit ? response.data.files.length > limit : false;
4389
+ output.info(files.length > 0 ? files.join("\n") : "No matching files.");
4390
+ if (response.data.truncated || wasClientTruncated) {
4391
+ output.info(`[truncated: ${response.data.total_files} total files]`);
4392
+ }
4393
+ }
4394
+ async function printBackendStatus(options, output) {
4395
+ const health = await readBackendHealth(options);
4396
+ output.info(health.ok ? `API: ${health.service} ready` : `API: unavailable (${health.message})`);
4397
+ }
4398
+ async function runSyncSession(role, roomCode, options, output) {
4399
+ await startSyncSession({
4400
+ apiBaseUrl: resolveApiBaseUrl(options),
4401
+ roomCode,
4402
+ role,
4403
+ cwd: process4.cwd(),
4404
+ output
4405
+ });
4406
+ }
4407
+ function formatScrubReport(findings) {
4408
+ const lines = [`Found ${findings.length} possible secret${findings.length === 1 ? "" : "s"}:`];
4409
+ for (const finding of findings) {
4410
+ const location = finding.line ? `${finding.filePath}:${finding.line}` : finding.filePath;
4411
+ const status = finding.verified ? "verified" : "unverified";
4412
+ lines.push(`- ${location} ${finding.detectorName} ${status}`);
4413
+ }
4414
+ return lines.join("\n");
4415
+ }
4416
+ function formatTranscriptRecords(records) {
4417
+ if (records.length === 0) {
4418
+ return "No transcript files found.";
4419
+ }
4420
+ return records.map((record, index) => {
4421
+ const title = record.title ? `
4422
+ ${singleLine(record.title)}` : "";
4423
+ const cwd = record.cwd ? `
4424
+ cwd ${record.cwd}` : "";
4425
+ const session = record.sessionId ? `
4426
+ session ${record.sessionId}` : "";
4427
+ return `${index + 1}. ${record.source} ${record.updatedAt}
4428
+ ${record.filePath}${session}${cwd}${title}`;
4429
+ }).join("\n");
4430
+ }
4431
+ function formatTranscriptEntries(entries) {
4432
+ if (entries.length === 0) {
4433
+ return "No transcript entries found.";
4434
+ }
4435
+ return entries.map((entry) => {
4436
+ const when = entry.timestamp ? ` ${entry.timestamp}` : "";
4437
+ return `[${entry.source}] ${entry.role}${when}
4438
+ ${entry.text.trim()}`;
4439
+ }).join("\n\n");
4440
+ }
4441
+ function createKnowledgesApi(options) {
4442
+ const client = createCngApiClient(options);
4443
+ return {
4444
+ getCatalog: () => client.harnessKnowledges.getHarnessKnowledgesCatalog(),
4445
+ listAudiences: () => client.harnessKnowledges.listHarnessKnowledgesAudiences(),
4446
+ search: (query, limit) => client.harnessKnowledges.searchHarnessKnowledges({
4447
+ q: query,
4448
+ limit
4449
+ }),
4450
+ listSubskills: () => client.harnessKnowledges.listHarnessKnowledgesSubskills(),
4451
+ listFiles: ({ query, audience, limit }) => client.harnessKnowledges.listHarnessSubskillAssets({
4452
+ ...query ? { q: query } : {},
4453
+ ...audience ? { audience } : {},
4454
+ limit
4455
+ }),
4456
+ read: ({ filePath, offset, limit }) => client.harnessFilesystem.getHarnessFilesystemRead({
4457
+ file_path: filePath,
4458
+ offset,
4459
+ limit
4460
+ }),
4461
+ grep: ({ pattern, path: path6, include, mode, context, ignoreCase }) => client.harnessFilesystem.getHarnessFilesystemGrep({
4462
+ pattern,
4463
+ path: path6,
4464
+ include,
4465
+ output_mode: mode,
4466
+ context,
4467
+ case_insensitive: ignoreCase ? "true" : void 0
4468
+ }),
4469
+ glob: ({ pattern, path: path6 }) => client.harnessFilesystem.getHarnessFilesystemGlob({
4470
+ pattern,
4471
+ path: path6
4472
+ })
4473
+ };
4474
+ }
4475
+ function coerceLimit(value, defaultValue, maxValue = 100) {
4476
+ const normalizedValue = coerceOptionalNumber(value);
4477
+ if (normalizedValue === void 0 || Number.isNaN(normalizedValue)) {
4478
+ return defaultValue;
4479
+ }
4480
+ return Math.max(defaultValue === 0 ? 0 : 1, Math.min(maxValue, Math.trunc(normalizedValue)));
4481
+ }
4482
+ function coerceOptionalNumber(value) {
4483
+ if (value === void 0 || value === "") {
4484
+ return void 0;
4485
+ }
4486
+ return Number(value);
4487
+ }
4488
+ function normalizeAudienceId(value) {
4489
+ if (value === void 0) {
4490
+ return void 0;
4491
+ }
4492
+ switch (value) {
4493
+ case "all":
4494
+ case "operators":
4495
+ case "builders":
4496
+ case "researchers":
4497
+ case "agent-makers":
4498
+ return value;
4499
+ default:
4500
+ throw new Error(
4501
+ `Unknown audience "${value}". Run cngkit knowledges audiences to see supported values.`
4502
+ );
4503
+ }
4504
+ }
4505
+ function normalizeGrepMode(value) {
4506
+ if (value === void 0) {
4507
+ return "content";
4508
+ }
4509
+ switch (value) {
4510
+ case "content":
4511
+ case "files_with_matches":
4512
+ case "count":
4513
+ return value;
4514
+ default:
4515
+ throw new Error("Unknown grep mode. Use one of: content, files_with_matches, count.");
4516
+ }
4517
+ }
4518
+ function normalizeTranscriptSource(value) {
4519
+ if (value === void 0) {
4520
+ return "all";
4521
+ }
4522
+ switch (value) {
4523
+ case "all":
4524
+ case "codex":
4525
+ case "claude":
4526
+ return value;
4527
+ default:
4528
+ throw new Error("Unknown transcript source. Use one of: all, codex, claude.");
4529
+ }
4530
+ }
4531
+ function singleLine(value) {
4532
+ return value.replace(/\s+/g, " ").trim();
4533
+ }
4534
+ function formatJson(value) {
4535
+ return JSON.stringify(value, null, 2);
4536
+ }
4537
+ function optionalJoinedArgument(values) {
4538
+ return values.length > 0 ? values.join(" ") : void 0;
4539
+ }
4540
+ function normalizeCatalogPath(value) {
4541
+ const trimmed = value.trim();
4542
+ if (trimmed === "/" || trimmed === "") {
4543
+ return "skills";
4544
+ }
4545
+ const relativePath = trimmed.replace(/^\/+/, "");
4546
+ if (relativePath.startsWith("skills/knowledges/")) {
4547
+ return relativePath;
4548
+ }
4549
+ const [firstSegment, ...restSegments] = relativePath.split("/");
4550
+ if (!firstSegment || restSegments.length === 0) {
4551
+ return relativePath;
4552
+ }
4553
+ switch (firstSegment) {
4554
+ case "concepts":
4555
+ case "domains":
4556
+ case "formats":
4557
+ case "languages":
4558
+ case "libraries":
4559
+ case "patterns":
4560
+ case "platforms":
4561
+ case "procedures":
4562
+ case "protocols":
4563
+ case "tools":
4564
+ return `skills/knowledges/subskills/${firstSegment}/${restSegments.join("/")}`;
4565
+ default:
4566
+ return relativePath;
4567
+ }
4568
+ }
4569
+
4570
+ export {
4571
+ runLoginCommand,
4572
+ runShareCommand,
4573
+ runJoinCommand,
4574
+ runScrubCommand,
4575
+ runTranscriptCommand,
4576
+ runKnowStatusCommand,
4577
+ runKnowAudiencesCommand,
4578
+ runKnowSearchCommand,
4579
+ runKnowListCommand,
4580
+ runKnowFilesCommand,
4581
+ runKnowReadCommand,
4582
+ runKnowGrepCommand,
4583
+ runKnowGlobCommand
4584
+ };
4585
+ //# sourceMappingURL=chunk-HBBUFPJG.js.map