@ocxp/client 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3913 @@
1
+ import { z } from 'zod';
2
+
3
+ // src/generated/core/bodySerializer.gen.ts
4
+ var serializeUrlSearchParamsPair = (data, key, value) => {
5
+ if (typeof value === "string") {
6
+ data.append(key, value);
7
+ } else {
8
+ data.append(key, JSON.stringify(value));
9
+ }
10
+ };
11
+ var jsonBodySerializer = {
12
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
13
+ };
14
+ var urlSearchParamsBodySerializer = {
15
+ bodySerializer: (body) => {
16
+ const data = new URLSearchParams();
17
+ Object.entries(body).forEach(([key, value]) => {
18
+ if (value === void 0 || value === null) {
19
+ return;
20
+ }
21
+ if (Array.isArray(value)) {
22
+ value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
23
+ } else {
24
+ serializeUrlSearchParamsPair(data, key, value);
25
+ }
26
+ });
27
+ return data.toString();
28
+ }
29
+ };
30
+
31
+ // src/generated/core/serverSentEvents.gen.ts
32
+ var createSseClient = ({
33
+ onRequest,
34
+ onSseError,
35
+ onSseEvent,
36
+ responseTransformer,
37
+ responseValidator,
38
+ sseDefaultRetryDelay,
39
+ sseMaxRetryAttempts,
40
+ sseMaxRetryDelay,
41
+ sseSleepFn,
42
+ url,
43
+ ...options
44
+ }) => {
45
+ let lastEventId;
46
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
47
+ const createStream = async function* () {
48
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
49
+ let attempt = 0;
50
+ const signal = options.signal ?? new AbortController().signal;
51
+ while (true) {
52
+ if (signal.aborted) break;
53
+ attempt++;
54
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
55
+ if (lastEventId !== void 0) {
56
+ headers.set("Last-Event-ID", lastEventId);
57
+ }
58
+ try {
59
+ const requestInit = {
60
+ redirect: "follow",
61
+ ...options,
62
+ body: options.serializedBody,
63
+ headers,
64
+ signal
65
+ };
66
+ let request = new Request(url, requestInit);
67
+ if (onRequest) {
68
+ request = await onRequest(url, requestInit);
69
+ }
70
+ const _fetch = options.fetch ?? globalThis.fetch;
71
+ const response = await _fetch(request);
72
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
73
+ if (!response.body) throw new Error("No body in SSE response");
74
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
75
+ let buffer = "";
76
+ const abortHandler = () => {
77
+ try {
78
+ reader.cancel();
79
+ } catch {
80
+ }
81
+ };
82
+ signal.addEventListener("abort", abortHandler);
83
+ try {
84
+ while (true) {
85
+ const { done, value } = await reader.read();
86
+ if (done) break;
87
+ buffer += value;
88
+ buffer = buffer.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
89
+ const chunks = buffer.split("\n\n");
90
+ buffer = chunks.pop() ?? "";
91
+ for (const chunk of chunks) {
92
+ const lines = chunk.split("\n");
93
+ const dataLines = [];
94
+ let eventName;
95
+ for (const line of lines) {
96
+ if (line.startsWith("data:")) {
97
+ dataLines.push(line.replace(/^data:\s*/, ""));
98
+ } else if (line.startsWith("event:")) {
99
+ eventName = line.replace(/^event:\s*/, "");
100
+ } else if (line.startsWith("id:")) {
101
+ lastEventId = line.replace(/^id:\s*/, "");
102
+ } else if (line.startsWith("retry:")) {
103
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
104
+ if (!Number.isNaN(parsed)) {
105
+ retryDelay = parsed;
106
+ }
107
+ }
108
+ }
109
+ let data;
110
+ let parsedJson = false;
111
+ if (dataLines.length) {
112
+ const rawData = dataLines.join("\n");
113
+ try {
114
+ data = JSON.parse(rawData);
115
+ parsedJson = true;
116
+ } catch {
117
+ data = rawData;
118
+ }
119
+ }
120
+ if (parsedJson) {
121
+ if (responseValidator) {
122
+ await responseValidator(data);
123
+ }
124
+ if (responseTransformer) {
125
+ data = await responseTransformer(data);
126
+ }
127
+ }
128
+ onSseEvent?.({
129
+ data,
130
+ event: eventName,
131
+ id: lastEventId,
132
+ retry: retryDelay
133
+ });
134
+ if (dataLines.length) {
135
+ yield data;
136
+ }
137
+ }
138
+ }
139
+ } finally {
140
+ signal.removeEventListener("abort", abortHandler);
141
+ reader.releaseLock();
142
+ }
143
+ break;
144
+ } catch (error) {
145
+ onSseError?.(error);
146
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
147
+ break;
148
+ }
149
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
150
+ await sleep(backoff);
151
+ }
152
+ }
153
+ };
154
+ const stream = createStream();
155
+ return { stream };
156
+ };
157
+
158
+ // src/generated/core/pathSerializer.gen.ts
159
+ var separatorArrayExplode = (style) => {
160
+ switch (style) {
161
+ case "label":
162
+ return ".";
163
+ case "matrix":
164
+ return ";";
165
+ case "simple":
166
+ return ",";
167
+ default:
168
+ return "&";
169
+ }
170
+ };
171
+ var separatorArrayNoExplode = (style) => {
172
+ switch (style) {
173
+ case "form":
174
+ return ",";
175
+ case "pipeDelimited":
176
+ return "|";
177
+ case "spaceDelimited":
178
+ return "%20";
179
+ default:
180
+ return ",";
181
+ }
182
+ };
183
+ var separatorObjectExplode = (style) => {
184
+ switch (style) {
185
+ case "label":
186
+ return ".";
187
+ case "matrix":
188
+ return ";";
189
+ case "simple":
190
+ return ",";
191
+ default:
192
+ return "&";
193
+ }
194
+ };
195
+ var serializeArrayParam = ({
196
+ allowReserved,
197
+ explode,
198
+ name,
199
+ style,
200
+ value
201
+ }) => {
202
+ if (!explode) {
203
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
204
+ switch (style) {
205
+ case "label":
206
+ return `.${joinedValues2}`;
207
+ case "matrix":
208
+ return `;${name}=${joinedValues2}`;
209
+ case "simple":
210
+ return joinedValues2;
211
+ default:
212
+ return `${name}=${joinedValues2}`;
213
+ }
214
+ }
215
+ const separator = separatorArrayExplode(style);
216
+ const joinedValues = value.map((v) => {
217
+ if (style === "label" || style === "simple") {
218
+ return allowReserved ? v : encodeURIComponent(v);
219
+ }
220
+ return serializePrimitiveParam({
221
+ allowReserved,
222
+ name,
223
+ value: v
224
+ });
225
+ }).join(separator);
226
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
227
+ };
228
+ var serializePrimitiveParam = ({
229
+ allowReserved,
230
+ name,
231
+ value
232
+ }) => {
233
+ if (value === void 0 || value === null) {
234
+ return "";
235
+ }
236
+ if (typeof value === "object") {
237
+ throw new Error(
238
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
239
+ );
240
+ }
241
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
242
+ };
243
+ var serializeObjectParam = ({
244
+ allowReserved,
245
+ explode,
246
+ name,
247
+ style,
248
+ value,
249
+ valueOnly
250
+ }) => {
251
+ if (value instanceof Date) {
252
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
253
+ }
254
+ if (style !== "deepObject" && !explode) {
255
+ let values = [];
256
+ Object.entries(value).forEach(([key, v]) => {
257
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
258
+ });
259
+ const joinedValues2 = values.join(",");
260
+ switch (style) {
261
+ case "form":
262
+ return `${name}=${joinedValues2}`;
263
+ case "label":
264
+ return `.${joinedValues2}`;
265
+ case "matrix":
266
+ return `;${name}=${joinedValues2}`;
267
+ default:
268
+ return joinedValues2;
269
+ }
270
+ }
271
+ const separator = separatorObjectExplode(style);
272
+ const joinedValues = Object.entries(value).map(
273
+ ([key, v]) => serializePrimitiveParam({
274
+ allowReserved,
275
+ name: style === "deepObject" ? `${name}[${key}]` : key,
276
+ value: v
277
+ })
278
+ ).join(separator);
279
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
280
+ };
281
+
282
+ // src/generated/core/utils.gen.ts
283
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
284
+ var defaultPathSerializer = ({ path, url: _url }) => {
285
+ let url = _url;
286
+ const matches = _url.match(PATH_PARAM_RE);
287
+ if (matches) {
288
+ for (const match of matches) {
289
+ let explode = false;
290
+ let name = match.substring(1, match.length - 1);
291
+ let style = "simple";
292
+ if (name.endsWith("*")) {
293
+ explode = true;
294
+ name = name.substring(0, name.length - 1);
295
+ }
296
+ if (name.startsWith(".")) {
297
+ name = name.substring(1);
298
+ style = "label";
299
+ } else if (name.startsWith(";")) {
300
+ name = name.substring(1);
301
+ style = "matrix";
302
+ }
303
+ const value = path[name];
304
+ if (value === void 0 || value === null) {
305
+ continue;
306
+ }
307
+ if (Array.isArray(value)) {
308
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
309
+ continue;
310
+ }
311
+ if (typeof value === "object") {
312
+ url = url.replace(
313
+ match,
314
+ serializeObjectParam({
315
+ explode,
316
+ name,
317
+ style,
318
+ value,
319
+ valueOnly: true
320
+ })
321
+ );
322
+ continue;
323
+ }
324
+ if (style === "matrix") {
325
+ url = url.replace(
326
+ match,
327
+ `;${serializePrimitiveParam({
328
+ name,
329
+ value
330
+ })}`
331
+ );
332
+ continue;
333
+ }
334
+ const replaceValue = encodeURIComponent(
335
+ style === "label" ? `.${value}` : value
336
+ );
337
+ url = url.replace(match, replaceValue);
338
+ }
339
+ }
340
+ return url;
341
+ };
342
+ var getUrl = ({
343
+ baseUrl,
344
+ path,
345
+ query,
346
+ querySerializer,
347
+ url: _url
348
+ }) => {
349
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
350
+ let url = (baseUrl ?? "") + pathUrl;
351
+ if (path) {
352
+ url = defaultPathSerializer({ path, url });
353
+ }
354
+ let search = query ? querySerializer(query) : "";
355
+ if (search.startsWith("?")) {
356
+ search = search.substring(1);
357
+ }
358
+ if (search) {
359
+ url += `?${search}`;
360
+ }
361
+ return url;
362
+ };
363
+ function getValidRequestBody(options) {
364
+ const hasBody = options.body !== void 0;
365
+ const isSerializedBody = hasBody && options.bodySerializer;
366
+ if (isSerializedBody) {
367
+ if ("serializedBody" in options) {
368
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
369
+ return hasSerializedBody ? options.serializedBody : null;
370
+ }
371
+ return options.body !== "" ? options.body : null;
372
+ }
373
+ if (hasBody) {
374
+ return options.body;
375
+ }
376
+ return void 0;
377
+ }
378
+
379
+ // src/generated/core/auth.gen.ts
380
+ var getAuthToken = async (auth, callback) => {
381
+ const token = typeof callback === "function" ? await callback(auth) : callback;
382
+ if (!token) {
383
+ return;
384
+ }
385
+ if (auth.scheme === "bearer") {
386
+ return `Bearer ${token}`;
387
+ }
388
+ if (auth.scheme === "basic") {
389
+ return `Basic ${btoa(token)}`;
390
+ }
391
+ return token;
392
+ };
393
+
394
+ // src/generated/client/utils.gen.ts
395
+ var createQuerySerializer = ({
396
+ parameters = {},
397
+ ...args
398
+ } = {}) => {
399
+ const querySerializer = (queryParams) => {
400
+ const search = [];
401
+ if (queryParams && typeof queryParams === "object") {
402
+ for (const name in queryParams) {
403
+ const value = queryParams[name];
404
+ if (value === void 0 || value === null) {
405
+ continue;
406
+ }
407
+ const options = parameters[name] || args;
408
+ if (Array.isArray(value)) {
409
+ const serializedArray = serializeArrayParam({
410
+ allowReserved: options.allowReserved,
411
+ explode: true,
412
+ name,
413
+ style: "form",
414
+ value,
415
+ ...options.array
416
+ });
417
+ if (serializedArray) search.push(serializedArray);
418
+ } else if (typeof value === "object") {
419
+ const serializedObject = serializeObjectParam({
420
+ allowReserved: options.allowReserved,
421
+ explode: true,
422
+ name,
423
+ style: "deepObject",
424
+ value,
425
+ ...options.object
426
+ });
427
+ if (serializedObject) search.push(serializedObject);
428
+ } else {
429
+ const serializedPrimitive = serializePrimitiveParam({
430
+ allowReserved: options.allowReserved,
431
+ name,
432
+ value
433
+ });
434
+ if (serializedPrimitive) search.push(serializedPrimitive);
435
+ }
436
+ }
437
+ }
438
+ return search.join("&");
439
+ };
440
+ return querySerializer;
441
+ };
442
+ var getParseAs = (contentType) => {
443
+ if (!contentType) {
444
+ return "stream";
445
+ }
446
+ const cleanContent = contentType.split(";")[0]?.trim();
447
+ if (!cleanContent) {
448
+ return;
449
+ }
450
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
451
+ return "json";
452
+ }
453
+ if (cleanContent === "multipart/form-data") {
454
+ return "formData";
455
+ }
456
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
457
+ return "blob";
458
+ }
459
+ if (cleanContent.startsWith("text/")) {
460
+ return "text";
461
+ }
462
+ return;
463
+ };
464
+ var checkForExistence = (options, name) => {
465
+ if (!name) {
466
+ return false;
467
+ }
468
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
469
+ return true;
470
+ }
471
+ return false;
472
+ };
473
+ var setAuthParams = async ({
474
+ security,
475
+ ...options
476
+ }) => {
477
+ for (const auth of security) {
478
+ if (checkForExistence(options, auth.name)) {
479
+ continue;
480
+ }
481
+ const token = await getAuthToken(auth, options.auth);
482
+ if (!token) {
483
+ continue;
484
+ }
485
+ const name = auth.name ?? "Authorization";
486
+ switch (auth.in) {
487
+ case "query":
488
+ if (!options.query) {
489
+ options.query = {};
490
+ }
491
+ options.query[name] = token;
492
+ break;
493
+ case "cookie":
494
+ options.headers.append("Cookie", `${name}=${token}`);
495
+ break;
496
+ case "header":
497
+ default:
498
+ options.headers.set(name, token);
499
+ break;
500
+ }
501
+ }
502
+ };
503
+ var buildUrl = (options) => getUrl({
504
+ baseUrl: options.baseUrl,
505
+ path: options.path,
506
+ query: options.query,
507
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
508
+ url: options.url
509
+ });
510
+ var mergeConfigs = (a, b) => {
511
+ const config = { ...a, ...b };
512
+ if (config.baseUrl?.endsWith("/")) {
513
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
514
+ }
515
+ config.headers = mergeHeaders(a.headers, b.headers);
516
+ return config;
517
+ };
518
+ var headersEntries = (headers) => {
519
+ const entries = [];
520
+ headers.forEach((value, key) => {
521
+ entries.push([key, value]);
522
+ });
523
+ return entries;
524
+ };
525
+ var mergeHeaders = (...headers) => {
526
+ const mergedHeaders = new Headers();
527
+ for (const header of headers) {
528
+ if (!header) {
529
+ continue;
530
+ }
531
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
532
+ for (const [key, value] of iterator) {
533
+ if (value === null) {
534
+ mergedHeaders.delete(key);
535
+ } else if (Array.isArray(value)) {
536
+ for (const v of value) {
537
+ mergedHeaders.append(key, v);
538
+ }
539
+ } else if (value !== void 0) {
540
+ mergedHeaders.set(
541
+ key,
542
+ typeof value === "object" ? JSON.stringify(value) : value
543
+ );
544
+ }
545
+ }
546
+ }
547
+ return mergedHeaders;
548
+ };
549
+ var Interceptors = class {
550
+ fns = [];
551
+ clear() {
552
+ this.fns = [];
553
+ }
554
+ eject(id) {
555
+ const index = this.getInterceptorIndex(id);
556
+ if (this.fns[index]) {
557
+ this.fns[index] = null;
558
+ }
559
+ }
560
+ exists(id) {
561
+ const index = this.getInterceptorIndex(id);
562
+ return Boolean(this.fns[index]);
563
+ }
564
+ getInterceptorIndex(id) {
565
+ if (typeof id === "number") {
566
+ return this.fns[id] ? id : -1;
567
+ }
568
+ return this.fns.indexOf(id);
569
+ }
570
+ update(id, fn) {
571
+ const index = this.getInterceptorIndex(id);
572
+ if (this.fns[index]) {
573
+ this.fns[index] = fn;
574
+ return id;
575
+ }
576
+ return false;
577
+ }
578
+ use(fn) {
579
+ this.fns.push(fn);
580
+ return this.fns.length - 1;
581
+ }
582
+ };
583
+ var createInterceptors = () => ({
584
+ error: new Interceptors(),
585
+ request: new Interceptors(),
586
+ response: new Interceptors()
587
+ });
588
+ var defaultQuerySerializer = createQuerySerializer({
589
+ allowReserved: false,
590
+ array: {
591
+ explode: true,
592
+ style: "form"
593
+ },
594
+ object: {
595
+ explode: true,
596
+ style: "deepObject"
597
+ }
598
+ });
599
+ var defaultHeaders = {
600
+ "Content-Type": "application/json"
601
+ };
602
+ var createConfig = (override = {}) => ({
603
+ ...jsonBodySerializer,
604
+ headers: defaultHeaders,
605
+ parseAs: "auto",
606
+ querySerializer: defaultQuerySerializer,
607
+ ...override
608
+ });
609
+
610
+ // src/generated/client/client.gen.ts
611
+ var createClient = (config = {}) => {
612
+ let _config = mergeConfigs(createConfig(), config);
613
+ const getConfig = () => ({ ..._config });
614
+ const setConfig = (config2) => {
615
+ _config = mergeConfigs(_config, config2);
616
+ return getConfig();
617
+ };
618
+ const interceptors = createInterceptors();
619
+ const beforeRequest = async (options) => {
620
+ const opts = {
621
+ ..._config,
622
+ ...options,
623
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
624
+ headers: mergeHeaders(_config.headers, options.headers),
625
+ serializedBody: void 0
626
+ };
627
+ if (opts.security) {
628
+ await setAuthParams({
629
+ ...opts,
630
+ security: opts.security
631
+ });
632
+ }
633
+ if (opts.requestValidator) {
634
+ await opts.requestValidator(opts);
635
+ }
636
+ if (opts.body !== void 0 && opts.bodySerializer) {
637
+ opts.serializedBody = opts.bodySerializer(opts.body);
638
+ }
639
+ if (opts.body === void 0 || opts.serializedBody === "") {
640
+ opts.headers.delete("Content-Type");
641
+ }
642
+ const url = buildUrl(opts);
643
+ return { opts, url };
644
+ };
645
+ const request = async (options) => {
646
+ const { opts, url } = await beforeRequest(options);
647
+ const requestInit = {
648
+ redirect: "follow",
649
+ ...opts,
650
+ body: getValidRequestBody(opts)
651
+ };
652
+ let request2 = new Request(url, requestInit);
653
+ for (const fn of interceptors.request.fns) {
654
+ if (fn) {
655
+ request2 = await fn(request2, opts);
656
+ }
657
+ }
658
+ const _fetch = opts.fetch;
659
+ let response;
660
+ try {
661
+ response = await _fetch(request2);
662
+ } catch (error2) {
663
+ let finalError2 = error2;
664
+ for (const fn of interceptors.error.fns) {
665
+ if (fn) {
666
+ finalError2 = await fn(error2, void 0, request2, opts);
667
+ }
668
+ }
669
+ finalError2 = finalError2 || {};
670
+ if (opts.throwOnError) {
671
+ throw finalError2;
672
+ }
673
+ return opts.responseStyle === "data" ? void 0 : {
674
+ error: finalError2,
675
+ request: request2,
676
+ response: void 0
677
+ };
678
+ }
679
+ for (const fn of interceptors.response.fns) {
680
+ if (fn) {
681
+ response = await fn(response, request2, opts);
682
+ }
683
+ }
684
+ const result = {
685
+ request: request2,
686
+ response
687
+ };
688
+ if (response.ok) {
689
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
690
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
691
+ let emptyData;
692
+ switch (parseAs) {
693
+ case "arrayBuffer":
694
+ case "blob":
695
+ case "text":
696
+ emptyData = await response[parseAs]();
697
+ break;
698
+ case "formData":
699
+ emptyData = new FormData();
700
+ break;
701
+ case "stream":
702
+ emptyData = response.body;
703
+ break;
704
+ case "json":
705
+ default:
706
+ emptyData = {};
707
+ break;
708
+ }
709
+ return opts.responseStyle === "data" ? emptyData : {
710
+ data: emptyData,
711
+ ...result
712
+ };
713
+ }
714
+ let data;
715
+ switch (parseAs) {
716
+ case "arrayBuffer":
717
+ case "blob":
718
+ case "formData":
719
+ case "json":
720
+ case "text":
721
+ data = await response[parseAs]();
722
+ break;
723
+ case "stream":
724
+ return opts.responseStyle === "data" ? response.body : {
725
+ data: response.body,
726
+ ...result
727
+ };
728
+ }
729
+ if (parseAs === "json") {
730
+ if (opts.responseValidator) {
731
+ await opts.responseValidator(data);
732
+ }
733
+ if (opts.responseTransformer) {
734
+ data = await opts.responseTransformer(data);
735
+ }
736
+ }
737
+ return opts.responseStyle === "data" ? data : {
738
+ data,
739
+ ...result
740
+ };
741
+ }
742
+ const textError = await response.text();
743
+ let jsonError;
744
+ try {
745
+ jsonError = JSON.parse(textError);
746
+ } catch {
747
+ }
748
+ const error = jsonError ?? textError;
749
+ let finalError = error;
750
+ for (const fn of interceptors.error.fns) {
751
+ if (fn) {
752
+ finalError = await fn(error, response, request2, opts);
753
+ }
754
+ }
755
+ finalError = finalError || {};
756
+ if (opts.throwOnError) {
757
+ throw finalError;
758
+ }
759
+ return opts.responseStyle === "data" ? void 0 : {
760
+ error: finalError,
761
+ ...result
762
+ };
763
+ };
764
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
765
+ const makeSseFn = (method) => async (options) => {
766
+ const { opts, url } = await beforeRequest(options);
767
+ return createSseClient({
768
+ ...opts,
769
+ body: opts.body,
770
+ headers: opts.headers,
771
+ method,
772
+ onRequest: async (url2, init) => {
773
+ let request2 = new Request(url2, init);
774
+ for (const fn of interceptors.request.fns) {
775
+ if (fn) {
776
+ request2 = await fn(request2, opts);
777
+ }
778
+ }
779
+ return request2;
780
+ },
781
+ url
782
+ });
783
+ };
784
+ return {
785
+ buildUrl,
786
+ connect: makeMethodFn("CONNECT"),
787
+ delete: makeMethodFn("DELETE"),
788
+ get: makeMethodFn("GET"),
789
+ getConfig,
790
+ head: makeMethodFn("HEAD"),
791
+ interceptors,
792
+ options: makeMethodFn("OPTIONS"),
793
+ patch: makeMethodFn("PATCH"),
794
+ post: makeMethodFn("POST"),
795
+ put: makeMethodFn("PUT"),
796
+ request,
797
+ setConfig,
798
+ sse: {
799
+ connect: makeSseFn("CONNECT"),
800
+ delete: makeSseFn("DELETE"),
801
+ get: makeSseFn("GET"),
802
+ head: makeSseFn("HEAD"),
803
+ options: makeSseFn("OPTIONS"),
804
+ patch: makeSseFn("PATCH"),
805
+ post: makeSseFn("POST"),
806
+ put: makeSseFn("PUT"),
807
+ trace: makeSseFn("TRACE")
808
+ },
809
+ trace: makeMethodFn("TRACE")
810
+ };
811
+ };
812
+
813
+ // src/generated/client.gen.ts
814
+ var client = createClient(
815
+ createConfig({
816
+ baseUrl: "https://ix8b43sg3j.execute-api.us-west-2.amazonaws.com"
817
+ })
818
+ );
819
+
820
+ // src/generated/sdk.gen.ts
821
+ var bulkReadContent = (options) => (options.client ?? client).post({
822
+ security: [{ scheme: "bearer", type: "http" }],
823
+ url: "/ocxp/context/{content_type}/bulk/read",
824
+ ...options,
825
+ headers: {
826
+ "Content-Type": "application/json",
827
+ ...options.headers
828
+ }
829
+ });
830
+ var bulkWriteContent = (options) => (options.client ?? client).post({
831
+ security: [{ scheme: "bearer", type: "http" }],
832
+ url: "/ocxp/context/{content_type}/bulk/write",
833
+ ...options,
834
+ headers: {
835
+ "Content-Type": "application/json",
836
+ ...options.headers
837
+ }
838
+ });
839
+ var bulkDeleteContent = (options) => (options.client ?? client).post({
840
+ security: [{ scheme: "bearer", type: "http" }],
841
+ url: "/ocxp/context/{content_type}/bulk/delete",
842
+ ...options,
843
+ headers: {
844
+ "Content-Type": "application/json",
845
+ ...options.headers
846
+ }
847
+ });
848
+ var listSessions = (options) => (options?.client ?? client).get({
849
+ security: [{ scheme: "bearer", type: "http" }],
850
+ url: "/ocxp/session",
851
+ ...options
852
+ });
853
+ var getSessionMessages = (options) => (options.client ?? client).get({
854
+ security: [{ scheme: "bearer", type: "http" }],
855
+ url: "/ocxp/session/{session_id}/messages",
856
+ ...options
857
+ });
858
+ var updateSessionMetadata = (options) => (options.client ?? client).post({
859
+ security: [{ scheme: "bearer", type: "http" }],
860
+ url: "/ocxp/session/{session_id}/metadata",
861
+ ...options,
862
+ headers: {
863
+ "Content-Type": "application/json",
864
+ ...options.headers
865
+ }
866
+ });
867
+ var forkSession = (options) => (options.client ?? client).post({
868
+ security: [{ scheme: "bearer", type: "http" }],
869
+ url: "/ocxp/session/{session_id}/fork",
870
+ ...options,
871
+ headers: {
872
+ "Content-Type": "application/json",
873
+ ...options.headers
874
+ }
875
+ });
876
+ var archiveSession = (options) => (options.client ?? client).post({
877
+ security: [{ scheme: "bearer", type: "http" }],
878
+ url: "/ocxp/session/{session_id}/archive",
879
+ ...options
880
+ });
881
+ var listProjects = (options) => (options?.client ?? client).get({
882
+ security: [{ scheme: "bearer", type: "http" }],
883
+ url: "/ocxp/project",
884
+ ...options
885
+ });
886
+ var createProject = (options) => (options.client ?? client).post({
887
+ security: [{ scheme: "bearer", type: "http" }],
888
+ url: "/ocxp/project",
889
+ ...options,
890
+ headers: {
891
+ "Content-Type": "application/json",
892
+ ...options.headers
893
+ }
894
+ });
895
+ var deleteProject = (options) => (options.client ?? client).delete({
896
+ security: [{ scheme: "bearer", type: "http" }],
897
+ url: "/ocxp/project/{project_id}",
898
+ ...options
899
+ });
900
+ var getProject = (options) => (options.client ?? client).get({
901
+ security: [{ scheme: "bearer", type: "http" }],
902
+ url: "/ocxp/project/{project_id}",
903
+ ...options
904
+ });
905
+ var updateProject = (options) => (options.client ?? client).put({
906
+ security: [{ scheme: "bearer", type: "http" }],
907
+ url: "/ocxp/project/{project_id}",
908
+ ...options,
909
+ headers: {
910
+ "Content-Type": "application/json",
911
+ ...options.headers
912
+ }
913
+ });
914
+ var addLinkedRepo = (options) => (options.client ?? client).post({
915
+ security: [{ scheme: "bearer", type: "http" }],
916
+ url: "/ocxp/project/{project_id}/repos",
917
+ ...options,
918
+ headers: {
919
+ "Content-Type": "application/json",
920
+ ...options.headers
921
+ }
922
+ });
923
+ var removeLinkedRepo = (options) => (options.client ?? client).delete({
924
+ security: [{ scheme: "bearer", type: "http" }],
925
+ url: "/ocxp/project/{project_id}/repos/{repo_id}",
926
+ ...options
927
+ });
928
+ var setDefaultRepo = (options) => (options.client ?? client).put({
929
+ security: [{ scheme: "bearer", type: "http" }],
930
+ url: "/ocxp/project/{project_id}/default-repo",
931
+ ...options,
932
+ headers: {
933
+ "Content-Type": "application/json",
934
+ ...options.headers
935
+ }
936
+ });
937
+ var getContextRepos = (options) => (options.client ?? client).get({
938
+ security: [{ scheme: "bearer", type: "http" }],
939
+ url: "/ocxp/project/{project_id}/context-repos",
940
+ ...options
941
+ });
942
+ var addMission = (options) => (options.client ?? client).post({
943
+ security: [{ scheme: "bearer", type: "http" }],
944
+ url: "/ocxp/project/{project_id}/missions",
945
+ ...options,
946
+ headers: {
947
+ "Content-Type": "application/json",
948
+ ...options.headers
949
+ }
950
+ });
951
+ var removeMission = (options) => (options.client ?? client).delete({
952
+ security: [{ scheme: "bearer", type: "http" }],
953
+ url: "/ocxp/project/{project_id}/missions/{mission_id}",
954
+ ...options
955
+ });
956
+ var getProjectDatabases = (options) => (options.client ?? client).get({
957
+ security: [{ scheme: "bearer", type: "http" }],
958
+ url: "/ocxp/project/{project_id}/databases",
959
+ ...options
960
+ });
961
+ var addDatabase = (options) => (options.client ?? client).post({
962
+ security: [{ scheme: "bearer", type: "http" }],
963
+ url: "/ocxp/project/{project_id}/databases",
964
+ ...options,
965
+ headers: {
966
+ "Content-Type": "application/json",
967
+ ...options.headers
968
+ }
969
+ });
970
+ var removeDatabase = (options) => (options.client ?? client).delete({
971
+ security: [{ scheme: "bearer", type: "http" }],
972
+ url: "/ocxp/project/{project_id}/databases/{database_id}",
973
+ ...options
974
+ });
975
+ var setDefaultDatabase = (options) => (options.client ?? client).put({
976
+ security: [{ scheme: "bearer", type: "http" }],
977
+ url: "/ocxp/project/{project_id}/default-database",
978
+ ...options,
979
+ headers: {
980
+ "Content-Type": "application/json",
981
+ ...options.headers
982
+ }
983
+ });
984
+ var listMissions = (options) => (options?.client ?? client).get({
985
+ security: [{ scheme: "bearer", type: "http" }],
986
+ url: "/ocxp/mission",
987
+ ...options
988
+ });
989
+ var createMission = (options) => (options.client ?? client).post({
990
+ security: [{ scheme: "bearer", type: "http" }],
991
+ url: "/ocxp/mission",
992
+ ...options,
993
+ headers: {
994
+ "Content-Type": "application/json",
995
+ ...options.headers
996
+ }
997
+ });
998
+ var deleteMission = (options) => (options.client ?? client).delete({
999
+ security: [{ scheme: "bearer", type: "http" }],
1000
+ url: "/ocxp/mission/{mission_id}",
1001
+ ...options
1002
+ });
1003
+ var getMission = (options) => (options.client ?? client).get({
1004
+ security: [{ scheme: "bearer", type: "http" }],
1005
+ url: "/ocxp/mission/{mission_id}",
1006
+ ...options
1007
+ });
1008
+ var updateMission = (options) => (options.client ?? client).put({
1009
+ security: [{ scheme: "bearer", type: "http" }],
1010
+ url: "/ocxp/mission/{mission_id}",
1011
+ ...options,
1012
+ headers: {
1013
+ "Content-Type": "application/json",
1014
+ ...options.headers
1015
+ }
1016
+ });
1017
+ var addSession = (options) => (options.client ?? client).post({
1018
+ security: [{ scheme: "bearer", type: "http" }],
1019
+ url: "/ocxp/mission/{mission_id}/sessions",
1020
+ ...options,
1021
+ headers: {
1022
+ "Content-Type": "application/json",
1023
+ ...options.headers
1024
+ }
1025
+ });
1026
+ var removeSession = (options) => (options.client ?? client).delete({
1027
+ security: [{ scheme: "bearer", type: "http" }],
1028
+ url: "/ocxp/mission/{mission_id}/sessions/{session_id}",
1029
+ ...options
1030
+ });
1031
+ var regenerateMission = (options) => (options.client ?? client).post({
1032
+ security: [{ scheme: "bearer", type: "http" }],
1033
+ url: "/ocxp/mission/{mission_id}/regenerate",
1034
+ ...options,
1035
+ headers: {
1036
+ "Content-Type": "application/json",
1037
+ ...options.headers
1038
+ }
1039
+ });
1040
+ var queryKnowledgeBase = (options) => (options.client ?? client).post({
1041
+ security: [{ scheme: "bearer", type: "http" }],
1042
+ url: "/ocxp/kb/query",
1043
+ ...options,
1044
+ headers: {
1045
+ "Content-Type": "application/json",
1046
+ ...options.headers
1047
+ }
1048
+ });
1049
+ var ragKnowledgeBase = (options) => (options.client ?? client).post({
1050
+ security: [{ scheme: "bearer", type: "http" }],
1051
+ url: "/ocxp/kb/rag",
1052
+ ...options,
1053
+ headers: {
1054
+ "Content-Type": "application/json",
1055
+ ...options.headers
1056
+ }
1057
+ });
1058
+ var listMemos = (options) => (options?.client ?? client).get({
1059
+ security: [{ scheme: "bearer", type: "http" }],
1060
+ url: "/ocxp/memo",
1061
+ ...options
1062
+ });
1063
+ var createMemo = (options) => (options.client ?? client).post({
1064
+ security: [{ scheme: "bearer", type: "http" }],
1065
+ url: "/ocxp/memo",
1066
+ ...options,
1067
+ headers: {
1068
+ "Content-Type": "application/json",
1069
+ ...options.headers
1070
+ }
1071
+ });
1072
+ var deleteMemo = (options) => (options.client ?? client).delete({
1073
+ security: [{ scheme: "bearer", type: "http" }],
1074
+ url: "/ocxp/memo/{memo_id}",
1075
+ ...options
1076
+ });
1077
+ var getMemo = (options) => (options.client ?? client).get({
1078
+ security: [{ scheme: "bearer", type: "http" }],
1079
+ url: "/ocxp/memo/{memo_id}",
1080
+ ...options
1081
+ });
1082
+ var getMemoForSource = (options) => (options.client ?? client).get({
1083
+ security: [{ scheme: "bearer", type: "http" }],
1084
+ url: "/ocxp/memo/source/{source_type}/{source_id}",
1085
+ ...options
1086
+ });
1087
+ var resolveMemo = (options) => (options.client ?? client).post({
1088
+ security: [{ scheme: "bearer", type: "http" }],
1089
+ url: "/ocxp/memo/{memo_id}/resolve",
1090
+ ...options,
1091
+ headers: {
1092
+ "Content-Type": "application/json",
1093
+ ...options.headers
1094
+ }
1095
+ });
1096
+ var acknowledgeMemo = (options) => (options.client ?? client).post({
1097
+ security: [{ scheme: "bearer", type: "http" }],
1098
+ url: "/ocxp/memo/{memo_id}/acknowledge",
1099
+ ...options
1100
+ });
1101
+ var ignoreMemo = (options) => (options.client ?? client).post({
1102
+ security: [{ scheme: "bearer", type: "http" }],
1103
+ url: "/ocxp/memo/{memo_id}/ignore",
1104
+ ...options
1105
+ });
1106
+ var downloadRepository = (options) => (options.client ?? client).post({
1107
+ security: [{ scheme: "bearer", type: "http" }],
1108
+ url: "/ocxp/repo/download",
1109
+ ...options,
1110
+ headers: {
1111
+ "Content-Type": "application/json",
1112
+ ...options.headers
1113
+ }
1114
+ });
1115
+ var getRepoDownloadStatus = (options) => (options.client ?? client).get({
1116
+ security: [{ scheme: "bearer", type: "http" }],
1117
+ url: "/ocxp/repo/status/{job_id}",
1118
+ ...options
1119
+ });
1120
+ var listDownloadedRepos = (options) => (options?.client ?? client).get({
1121
+ security: [{ scheme: "bearer", type: "http" }],
1122
+ url: "/ocxp/repo/list",
1123
+ ...options
1124
+ });
1125
+ var deleteRepo = (options) => (options.client ?? client).delete({
1126
+ security: [{ scheme: "bearer", type: "http" }],
1127
+ url: "/ocxp/repo/{repo_id}",
1128
+ ...options
1129
+ });
1130
+ var githubCheckAccess = (options) => (options.client ?? client).post({
1131
+ security: [{ scheme: "bearer", type: "http" }],
1132
+ url: "/ocxp/github/check-access",
1133
+ ...options,
1134
+ headers: {
1135
+ "Content-Type": "application/json",
1136
+ ...options.headers
1137
+ }
1138
+ });
1139
+ var githubListBranches = (options) => (options.client ?? client).post({
1140
+ security: [{ scheme: "bearer", type: "http" }],
1141
+ url: "/ocxp/github/branches",
1142
+ ...options,
1143
+ headers: {
1144
+ "Content-Type": "application/json",
1145
+ ...options.headers
1146
+ }
1147
+ });
1148
+ var githubGetContents = (options) => (options.client ?? client).post({
1149
+ security: [{ scheme: "bearer", type: "http" }],
1150
+ url: "/ocxp/github/contents",
1151
+ ...options,
1152
+ headers: {
1153
+ "Content-Type": "application/json",
1154
+ ...options.headers
1155
+ }
1156
+ });
1157
+ var listDatabases = (options) => (options?.client ?? client).get({
1158
+ security: [{ scheme: "bearer", type: "http" }],
1159
+ url: "/ocxp/database",
1160
+ ...options
1161
+ });
1162
+ var createDatabase = (options) => (options.client ?? client).post({
1163
+ security: [{ scheme: "bearer", type: "http" }],
1164
+ url: "/ocxp/database",
1165
+ ...options,
1166
+ headers: {
1167
+ "Content-Type": "application/json",
1168
+ ...options.headers
1169
+ }
1170
+ });
1171
+ var deleteDatabase = (options) => (options.client ?? client).delete({
1172
+ security: [{ scheme: "bearer", type: "http" }],
1173
+ url: "/ocxp/database/{database_id}",
1174
+ ...options
1175
+ });
1176
+ var getDatabase = (options) => (options.client ?? client).get({
1177
+ security: [{ scheme: "bearer", type: "http" }],
1178
+ url: "/ocxp/database/{database_id}",
1179
+ ...options
1180
+ });
1181
+ var updateDatabase = (options) => (options.client ?? client).put({
1182
+ security: [{ scheme: "bearer", type: "http" }],
1183
+ url: "/ocxp/database/{database_id}",
1184
+ ...options,
1185
+ headers: {
1186
+ "Content-Type": "application/json",
1187
+ ...options.headers
1188
+ }
1189
+ });
1190
+ var testDatabaseConnection = (options) => (options.client ?? client).post({
1191
+ security: [{ scheme: "bearer", type: "http" }],
1192
+ url: "/ocxp/database/{database_id}/test",
1193
+ ...options
1194
+ });
1195
+ var getSchema = (options) => (options?.client ?? client).get({
1196
+ security: [{ scheme: "bearer", type: "http" }],
1197
+ url: "/ocxp/context/database/schema",
1198
+ ...options
1199
+ });
1200
+ var getSample = (options) => (options.client ?? client).get({
1201
+ security: [{ scheme: "bearer", type: "http" }],
1202
+ url: "/ocxp/context/database/sample/{table_name}",
1203
+ ...options
1204
+ });
1205
+ var listTables = (options) => (options?.client ?? client).get({
1206
+ security: [{ scheme: "bearer", type: "http" }],
1207
+ url: "/ocxp/context/database/tables",
1208
+ ...options
1209
+ });
1210
+ var listContextDatabases = (options) => (options?.client ?? client).get({
1211
+ security: [{ scheme: "bearer", type: "http" }],
1212
+ url: "/ocxp/context/database/databases",
1213
+ ...options
1214
+ });
1215
+ var getContentTypes = (options) => (options?.client ?? client).get({
1216
+ security: [{ scheme: "bearer", type: "http" }],
1217
+ url: "/ocxp/context/types",
1218
+ ...options
1219
+ });
1220
+ var listContent = (options) => (options.client ?? client).get({
1221
+ security: [{ scheme: "bearer", type: "http" }],
1222
+ url: "/ocxp/context/{content_type}/list",
1223
+ ...options
1224
+ });
1225
+ var queryContent = (options) => (options.client ?? client).post({
1226
+ security: [{ scheme: "bearer", type: "http" }],
1227
+ url: "/ocxp/context/{content_type}/query",
1228
+ ...options,
1229
+ headers: {
1230
+ "Content-Type": "application/json",
1231
+ ...options.headers
1232
+ }
1233
+ });
1234
+ var searchContent = (options) => (options.client ?? client).get({
1235
+ security: [{ scheme: "bearer", type: "http" }],
1236
+ url: "/ocxp/context/{content_type}/search",
1237
+ ...options
1238
+ });
1239
+ var getContentTree = (options) => (options.client ?? client).get({
1240
+ security: [{ scheme: "bearer", type: "http" }],
1241
+ url: "/ocxp/context/{content_type}/tree",
1242
+ ...options
1243
+ });
1244
+ var getContentStats = (options) => (options.client ?? client).get({
1245
+ security: [{ scheme: "bearer", type: "http" }],
1246
+ url: "/ocxp/context/{content_type}/stats",
1247
+ ...options
1248
+ });
1249
+ var deleteContent = (options) => (options.client ?? client).delete({
1250
+ security: [{ scheme: "bearer", type: "http" }],
1251
+ url: "/ocxp/context/{content_type}/{content_id}",
1252
+ ...options
1253
+ });
1254
+ var readContent = (options) => (options.client ?? client).get({
1255
+ security: [{ scheme: "bearer", type: "http" }],
1256
+ url: "/ocxp/context/{content_type}/{content_id}",
1257
+ ...options
1258
+ });
1259
+ var writeContent = (options) => (options.client ?? client).post({
1260
+ security: [{ scheme: "bearer", type: "http" }],
1261
+ url: "/ocxp/context/{content_type}/{content_id}",
1262
+ ...options,
1263
+ headers: {
1264
+ "Content-Type": "application/json",
1265
+ ...options.headers
1266
+ }
1267
+ });
1268
+ var moveContent = (options) => (options.client ?? client).post({
1269
+ security: [{ scheme: "bearer", type: "http" }],
1270
+ url: "/ocxp/context/move",
1271
+ ...options,
1272
+ headers: {
1273
+ "Content-Type": "application/json",
1274
+ ...options.headers
1275
+ }
1276
+ });
1277
+ var lockContent = (options) => (options.client ?? client).post({
1278
+ security: [{ scheme: "bearer", type: "http" }],
1279
+ url: "/ocxp/context/lock",
1280
+ ...options,
1281
+ headers: {
1282
+ "Content-Type": "application/json",
1283
+ ...options.headers
1284
+ }
1285
+ });
1286
+ var unlockContent = (options) => (options.client ?? client).post({
1287
+ security: [{ scheme: "bearer", type: "http" }],
1288
+ url: "/ocxp/context/unlock",
1289
+ ...options,
1290
+ headers: {
1291
+ "Content-Type": "application/json",
1292
+ ...options.headers
1293
+ }
1294
+ });
1295
+ var toolCreateMission = (options) => (options.client ?? client).post({
1296
+ security: [{ scheme: "bearer", type: "http" }],
1297
+ url: "/tools/mission/create",
1298
+ ...options,
1299
+ headers: {
1300
+ "Content-Type": "application/json",
1301
+ ...options.headers
1302
+ }
1303
+ });
1304
+ var toolUpdateMission = (options) => (options.client ?? client).post({
1305
+ security: [{ scheme: "bearer", type: "http" }],
1306
+ url: "/tools/mission/{mission_id}/update",
1307
+ ...options,
1308
+ headers: {
1309
+ "Content-Type": "application/json",
1310
+ ...options.headers
1311
+ }
1312
+ });
1313
+ var getMissionContext = (options) => (options.client ?? client).get(
1314
+ {
1315
+ security: [{ scheme: "bearer", type: "http" }],
1316
+ url: "/tools/mission/{mission_id}/context",
1317
+ ...options
1318
+ }
1319
+ );
1320
+ var loginForAccessToken = (options) => (options.client ?? client).post({
1321
+ ...urlSearchParamsBodySerializer,
1322
+ url: "/auth/token",
1323
+ ...options,
1324
+ headers: {
1325
+ "Content-Type": "application/x-www-form-urlencoded",
1326
+ ...options.headers
1327
+ }
1328
+ });
1329
+ var login = (options) => (options.client ?? client).post({
1330
+ security: [{ scheme: "bearer", type: "http" }],
1331
+ url: "/auth/login",
1332
+ ...options,
1333
+ headers: {
1334
+ "Content-Type": "application/json",
1335
+ ...options.headers
1336
+ }
1337
+ });
1338
+ var refreshTokens = (options) => (options.client ?? client).post({
1339
+ security: [{ scheme: "bearer", type: "http" }],
1340
+ url: "/auth/refresh",
1341
+ ...options,
1342
+ headers: {
1343
+ "Content-Type": "application/json",
1344
+ ...options.headers
1345
+ }
1346
+ });
1347
+ var getAuthConfig = (options) => (options?.client ?? client).get({
1348
+ url: "/auth/config",
1349
+ ...options
1350
+ });
1351
+ var getCurrentUser = (options) => (options?.client ?? client).get({
1352
+ security: [{ scheme: "bearer", type: "http" }],
1353
+ url: "/auth/me",
1354
+ ...options
1355
+ });
1356
+ var listWorkspaces = (options) => (options?.client ?? client).get({
1357
+ security: [{ scheme: "bearer", type: "http" }],
1358
+ url: "/auth/workspaces",
1359
+ ...options
1360
+ });
1361
+
1362
+ // src/client.ts
1363
+ function extractData(response) {
1364
+ if (response.error) {
1365
+ throw new Error(
1366
+ typeof response.error === "object" && response.error !== null ? response.error.message || JSON.stringify(response.error) : String(response.error)
1367
+ );
1368
+ }
1369
+ return response.data;
1370
+ }
1371
+ var OCXPClient = class {
1372
+ client;
1373
+ workspace;
1374
+ tokenProvider;
1375
+ constructor(options) {
1376
+ this.workspace = options.workspace || "dev";
1377
+ this.tokenProvider = options.token;
1378
+ const config = createConfig({
1379
+ baseUrl: options.endpoint.replace(/\/$/, ""),
1380
+ throwOnError: true
1381
+ });
1382
+ this.client = createClient(config);
1383
+ }
1384
+ /**
1385
+ * Get headers including workspace and auth
1386
+ */
1387
+ async getHeaders() {
1388
+ const headers = {
1389
+ "X-Workspace": this.workspace
1390
+ };
1391
+ if (this.tokenProvider) {
1392
+ const token = typeof this.tokenProvider === "function" ? await this.tokenProvider() : this.tokenProvider;
1393
+ if (token) {
1394
+ headers["Authorization"] = `Bearer ${token}`;
1395
+ }
1396
+ }
1397
+ return headers;
1398
+ }
1399
+ /**
1400
+ * Set the workspace for subsequent operations
1401
+ */
1402
+ setWorkspace(workspace) {
1403
+ this.workspace = workspace;
1404
+ }
1405
+ /**
1406
+ * Get current workspace
1407
+ */
1408
+ getWorkspace() {
1409
+ return this.workspace;
1410
+ }
1411
+ /**
1412
+ * Get the underlying client for SDK function calls
1413
+ */
1414
+ getClient() {
1415
+ return this.client;
1416
+ }
1417
+ /**
1418
+ * Set the auth token or token provider
1419
+ */
1420
+ setToken(token) {
1421
+ this.tokenProvider = token;
1422
+ }
1423
+ // ============== Content Types ==============
1424
+ /**
1425
+ * Get available content types with metadata
1426
+ */
1427
+ async getContentTypes(counts = false) {
1428
+ const headers = await this.getHeaders();
1429
+ const response = await getContentTypes({
1430
+ client: this.client,
1431
+ query: { counts },
1432
+ headers
1433
+ });
1434
+ const data = extractData(response);
1435
+ return {
1436
+ types: data.types || [],
1437
+ total: data.total || 0
1438
+ };
1439
+ }
1440
+ // ============== CRUD Operations ==============
1441
+ /**
1442
+ * List content of a specific type
1443
+ */
1444
+ async list(type, path, limit) {
1445
+ const headers = await this.getHeaders();
1446
+ const response = await listContent({
1447
+ client: this.client,
1448
+ path: { content_type: type },
1449
+ query: { path, limit },
1450
+ headers
1451
+ });
1452
+ const data = extractData(response);
1453
+ return {
1454
+ entries: data.entries || [],
1455
+ cursor: data.cursor,
1456
+ hasMore: data.has_more || false,
1457
+ total: data.total || 0
1458
+ };
1459
+ }
1460
+ /**
1461
+ * Read content by ID
1462
+ */
1463
+ async read(type, id) {
1464
+ const headers = await this.getHeaders();
1465
+ const response = await readContent({
1466
+ client: this.client,
1467
+ path: { content_type: type, content_id: id },
1468
+ headers
1469
+ });
1470
+ const data = extractData(response);
1471
+ return {
1472
+ content: data.content || "",
1473
+ size: data.size,
1474
+ mtime: data.mtime,
1475
+ encoding: data.encoding,
1476
+ metadata: data.metadata
1477
+ };
1478
+ }
1479
+ /**
1480
+ * Write content
1481
+ */
1482
+ async write(type, id, content, options) {
1483
+ const headers = await this.getHeaders();
1484
+ const body = {
1485
+ content,
1486
+ encoding: options?.encoding || "utf-8",
1487
+ etag: options?.etag,
1488
+ ifNotExists: options?.ifNotExists
1489
+ };
1490
+ const response = await writeContent({
1491
+ client: this.client,
1492
+ path: { content_type: type, content_id: id },
1493
+ body,
1494
+ headers
1495
+ });
1496
+ const data = extractData(response);
1497
+ return {
1498
+ path: data.path || `${type}/${id}`,
1499
+ etag: data.etag
1500
+ };
1501
+ }
1502
+ /**
1503
+ * Delete content
1504
+ */
1505
+ async delete(type, id, recursive = false, confirm = false) {
1506
+ const headers = await this.getHeaders();
1507
+ const response = await deleteContent({
1508
+ client: this.client,
1509
+ path: { content_type: type, content_id: id },
1510
+ query: { recursive, confirm },
1511
+ headers
1512
+ });
1513
+ const data = extractData(response);
1514
+ return {
1515
+ deleted: data.deleted ?? true,
1516
+ path: data.path || `${type}/${id}`
1517
+ };
1518
+ }
1519
+ // ============== Query & Search ==============
1520
+ /**
1521
+ * Query content with filters
1522
+ */
1523
+ async query(type, filters, limit) {
1524
+ const headers = await this.getHeaders();
1525
+ return queryContent({
1526
+ client: this.client,
1527
+ path: { content_type: type },
1528
+ body: { filters: filters || [], limit: limit || 100 },
1529
+ headers
1530
+ });
1531
+ }
1532
+ /**
1533
+ * Full-text search
1534
+ */
1535
+ async search(type, q, limit) {
1536
+ const headers = await this.getHeaders();
1537
+ return searchContent({
1538
+ client: this.client,
1539
+ path: { content_type: type },
1540
+ query: { q, limit },
1541
+ headers
1542
+ });
1543
+ }
1544
+ // ============== Tree & Stats ==============
1545
+ /**
1546
+ * Get hierarchical tree structure from S3 context
1547
+ */
1548
+ async tree(type, path, depth) {
1549
+ const headers = await this.getHeaders();
1550
+ const response = await getContentTree({
1551
+ client: this.client,
1552
+ path: { content_type: type },
1553
+ query: { path, depth },
1554
+ headers
1555
+ });
1556
+ return extractData(response);
1557
+ }
1558
+ /**
1559
+ * Get content statistics
1560
+ */
1561
+ async stats(type, path) {
1562
+ const headers = await this.getHeaders();
1563
+ return getContentStats({
1564
+ client: this.client,
1565
+ path: { content_type: type },
1566
+ query: { path },
1567
+ headers
1568
+ });
1569
+ }
1570
+ // ============== Bulk Operations ==============
1571
+ /**
1572
+ * Read multiple items at once
1573
+ */
1574
+ async bulkRead(type, ids) {
1575
+ const headers = await this.getHeaders();
1576
+ return bulkReadContent({
1577
+ client: this.client,
1578
+ path: { content_type: type },
1579
+ body: { ids },
1580
+ headers
1581
+ });
1582
+ }
1583
+ /**
1584
+ * Write multiple items at once
1585
+ */
1586
+ async bulkWrite(type, items) {
1587
+ const headers = await this.getHeaders();
1588
+ return bulkWriteContent({
1589
+ client: this.client,
1590
+ path: { content_type: type },
1591
+ body: { items },
1592
+ headers
1593
+ });
1594
+ }
1595
+ /**
1596
+ * Delete multiple items at once
1597
+ */
1598
+ async bulkDelete(type, ids) {
1599
+ const headers = await this.getHeaders();
1600
+ return bulkDeleteContent({
1601
+ client: this.client,
1602
+ path: { content_type: type },
1603
+ body: { ids },
1604
+ headers
1605
+ });
1606
+ }
1607
+ // ============== Knowledge Base ==============
1608
+ /**
1609
+ * Semantic search in Knowledge Base with optional external docs fallback
1610
+ */
1611
+ async kbQuery(query, options) {
1612
+ const headers = await this.getHeaders();
1613
+ const body = {
1614
+ query,
1615
+ search_type: options?.searchType || "SEMANTIC",
1616
+ max_results: options?.maxResults || 5,
1617
+ doc_id: options?.docId,
1618
+ repo_ids: options?.repoIds,
1619
+ project_id: options?.projectId,
1620
+ mission_id: options?.missionId,
1621
+ enable_fallback: options?.enableFallback ?? true,
1622
+ fallback_threshold: options?.fallbackThreshold ?? 0.5,
1623
+ persist_external_docs: options?.persistExternalDocs ?? true
1624
+ };
1625
+ const response = await queryKnowledgeBase({
1626
+ client: this.client,
1627
+ body,
1628
+ headers
1629
+ });
1630
+ return extractData(response);
1631
+ }
1632
+ /**
1633
+ * RAG with citations
1634
+ */
1635
+ async kbRag(query, sessionId) {
1636
+ const headers = await this.getHeaders();
1637
+ const response = await ragKnowledgeBase({
1638
+ client: this.client,
1639
+ body: { query, session_id: sessionId },
1640
+ headers
1641
+ });
1642
+ return extractData(response);
1643
+ }
1644
+ // ============== Mission Operations ==============
1645
+ /**
1646
+ * List all missions in workspace
1647
+ */
1648
+ async listMissions(options) {
1649
+ const headers = await this.getHeaders();
1650
+ const response = await listMissions({
1651
+ client: this.client,
1652
+ query: {
1653
+ project_id: options?.projectId,
1654
+ status: options?.status,
1655
+ limit: options?.limit
1656
+ },
1657
+ headers
1658
+ });
1659
+ return extractData(response);
1660
+ }
1661
+ /**
1662
+ * Create a new mission with auto-generated UUID
1663
+ */
1664
+ async createMission(title, description, projectId, goals) {
1665
+ const headers = await this.getHeaders();
1666
+ const body = {
1667
+ title,
1668
+ description,
1669
+ project_id: projectId,
1670
+ goals
1671
+ };
1672
+ const response = await createMission({
1673
+ client: this.client,
1674
+ body,
1675
+ headers
1676
+ });
1677
+ return extractData(response);
1678
+ }
1679
+ /**
1680
+ * Get mission by ID
1681
+ */
1682
+ async getMission(missionId) {
1683
+ const headers = await this.getHeaders();
1684
+ const response = await getMission({
1685
+ client: this.client,
1686
+ path: { mission_id: missionId },
1687
+ headers
1688
+ });
1689
+ return extractData(response);
1690
+ }
1691
+ /**
1692
+ * Update mission
1693
+ */
1694
+ async updateMission(missionId, updates) {
1695
+ const headers = await this.getHeaders();
1696
+ const response = await updateMission({
1697
+ client: this.client,
1698
+ path: { mission_id: missionId },
1699
+ body: updates,
1700
+ headers
1701
+ });
1702
+ return extractData(response);
1703
+ }
1704
+ /**
1705
+ * Delete mission
1706
+ */
1707
+ async deleteMission(missionId) {
1708
+ const headers = await this.getHeaders();
1709
+ await deleteMission({
1710
+ client: this.client,
1711
+ path: { mission_id: missionId },
1712
+ headers
1713
+ });
1714
+ }
1715
+ /**
1716
+ * Add session to mission
1717
+ */
1718
+ async addMissionSession(missionId, sessionId) {
1719
+ const headers = await this.getHeaders();
1720
+ const response = await addSession({
1721
+ client: this.client,
1722
+ path: { mission_id: missionId },
1723
+ body: { session_id: sessionId },
1724
+ headers
1725
+ });
1726
+ return extractData(response);
1727
+ }
1728
+ /**
1729
+ * Remove session from mission
1730
+ */
1731
+ async removeMissionSession(missionId, sessionId) {
1732
+ const headers = await this.getHeaders();
1733
+ const response = await removeSession({
1734
+ client: this.client,
1735
+ path: { mission_id: missionId, session_id: sessionId },
1736
+ headers
1737
+ });
1738
+ return extractData(response);
1739
+ }
1740
+ /**
1741
+ * Regenerate mission - archives old docs and triggers AgentCore
1742
+ */
1743
+ async regenerateMission(missionId, options) {
1744
+ const headers = await this.getHeaders();
1745
+ const response = await regenerateMission({
1746
+ client: this.client,
1747
+ path: { mission_id: missionId },
1748
+ body: {
1749
+ ticket_id: options?.ticket_id,
1750
+ ticket_summary: options?.ticket_summary,
1751
+ ticket_description: options?.ticket_description,
1752
+ archive_old_docs: options?.archive_old_docs ?? true,
1753
+ auto_increment_version: options?.auto_increment_version ?? true
1754
+ },
1755
+ headers
1756
+ });
1757
+ return extractData(response);
1758
+ }
1759
+ /**
1760
+ * Download mission pack as ZIP file
1761
+ * @param missionId - Mission ID
1762
+ * @returns Blob containing ZIP file
1763
+ */
1764
+ async downloadMissionPack(missionId) {
1765
+ const headers = await this.getHeaders();
1766
+ const config = this.client.getConfig();
1767
+ const baseUrl = config.baseUrl || "";
1768
+ const response = await fetch(`${baseUrl}/ocxp/mission/${missionId}/download`, {
1769
+ method: "GET",
1770
+ headers: {
1771
+ ...headers,
1772
+ "X-Workspace": this.workspace
1773
+ }
1774
+ });
1775
+ if (!response.ok) {
1776
+ throw new Error(`Failed to download mission: ${response.status} ${response.statusText}`);
1777
+ }
1778
+ return await response.blob();
1779
+ }
1780
+ // ============== Tools ==============
1781
+ /**
1782
+ * Get mission context for agents
1783
+ */
1784
+ async getMissionContext(missionId) {
1785
+ const headers = await this.getHeaders();
1786
+ return getMissionContext({
1787
+ client: this.client,
1788
+ path: { mission_id: missionId },
1789
+ headers
1790
+ });
1791
+ }
1792
+ // ============== Locking ==============
1793
+ /**
1794
+ * Acquire exclusive lock on content
1795
+ * @param contentType - Content type (e.g., "mission")
1796
+ * @param contentId - Content ID (e.g., "my-mission")
1797
+ * @param ttl - Lock time-to-live in seconds
1798
+ */
1799
+ async lock(contentType, contentId, ttl) {
1800
+ const headers = await this.getHeaders();
1801
+ return lockContent({
1802
+ client: this.client,
1803
+ body: {
1804
+ content_type: contentType,
1805
+ content_id: contentId,
1806
+ ttl
1807
+ },
1808
+ headers
1809
+ });
1810
+ }
1811
+ /**
1812
+ * Release exclusive lock
1813
+ * @param contentType - Content type
1814
+ * @param contentId - Content ID
1815
+ */
1816
+ async unlock(contentType, contentId) {
1817
+ const headers = await this.getHeaders();
1818
+ return unlockContent({
1819
+ client: this.client,
1820
+ body: {
1821
+ content_type: contentType,
1822
+ content_id: contentId
1823
+ },
1824
+ headers
1825
+ });
1826
+ }
1827
+ /**
1828
+ * Move/rename content
1829
+ * @param source - Source path (e.g., "mission/old-id")
1830
+ * @param destination - Destination path (e.g., "mission/new-id")
1831
+ * @param overwrite - Whether to overwrite existing content at destination
1832
+ */
1833
+ async move(source, destination, overwrite = false) {
1834
+ const headers = await this.getHeaders();
1835
+ const response = await moveContent({
1836
+ client: this.client,
1837
+ body: { source, destination, overwrite },
1838
+ headers
1839
+ });
1840
+ return extractData(response);
1841
+ }
1842
+ // ============== GitHub API Proxy ==============
1843
+ /**
1844
+ * Check if a repository is accessible
1845
+ * @param repoUrl - Full GitHub repository URL
1846
+ */
1847
+ async githubCheckAccess(repoUrl) {
1848
+ const headers = await this.getHeaders();
1849
+ const response = await githubCheckAccess({
1850
+ client: this.client,
1851
+ body: { repo_url: repoUrl },
1852
+ headers
1853
+ });
1854
+ return extractData(response);
1855
+ }
1856
+ /**
1857
+ * List branches for a repository
1858
+ * @param repoUrl - Full GitHub repository URL
1859
+ */
1860
+ async githubListBranches(repoUrl) {
1861
+ const headers = await this.getHeaders();
1862
+ const response = await githubListBranches({
1863
+ client: this.client,
1864
+ body: { repo_url: repoUrl },
1865
+ headers
1866
+ });
1867
+ return extractData(response);
1868
+ }
1869
+ /**
1870
+ * Get repository contents at a path
1871
+ * @param repoUrl - Full GitHub repository URL
1872
+ * @param path - Path within the repository
1873
+ * @param ref - Git ref (branch, tag, or commit)
1874
+ */
1875
+ async githubGetContents(repoUrl, path = "", ref) {
1876
+ const headers = await this.getHeaders();
1877
+ const response = await githubGetContents({
1878
+ client: this.client,
1879
+ body: { repo_url: repoUrl, path, ref },
1880
+ headers
1881
+ });
1882
+ return extractData(response);
1883
+ }
1884
+ // ============== Repository Management ==============
1885
+ /**
1886
+ * Download repository and trigger vectorization
1887
+ * @param repoUrl - Full GitHub repository URL
1888
+ * @param branch - Optional branch (default: main)
1889
+ * @param options - Download options (mode, repo_type, path)
1890
+ */
1891
+ async downloadRepository(repoUrl, branch, options) {
1892
+ const headers = await this.getHeaders();
1893
+ const response = await downloadRepository({
1894
+ client: this.client,
1895
+ body: {
1896
+ repo_url: repoUrl,
1897
+ branch,
1898
+ mode: options?.mode,
1899
+ repo_type: options?.repo_type,
1900
+ path: options?.path
1901
+ },
1902
+ headers
1903
+ });
1904
+ return extractData(response);
1905
+ }
1906
+ /**
1907
+ * Get repository download status
1908
+ */
1909
+ async getRepoStatus(jobId) {
1910
+ const headers = await this.getHeaders();
1911
+ const response = await getRepoDownloadStatus({
1912
+ client: this.client,
1913
+ path: { job_id: jobId },
1914
+ headers
1915
+ });
1916
+ return extractData(response);
1917
+ }
1918
+ /**
1919
+ * List all downloaded repositories in workspace
1920
+ */
1921
+ async listRepos() {
1922
+ const headers = await this.getHeaders();
1923
+ const response = await listDownloadedRepos({
1924
+ client: this.client,
1925
+ headers
1926
+ });
1927
+ return extractData(response);
1928
+ }
1929
+ /**
1930
+ * Delete a downloaded repository by its UUID
1931
+ */
1932
+ async deleteRepo(repoId) {
1933
+ const headers = await this.getHeaders();
1934
+ const response = await deleteRepo({
1935
+ client: this.client,
1936
+ path: { repo_id: repoId },
1937
+ headers
1938
+ });
1939
+ return extractData(response);
1940
+ }
1941
+ // ============== Database Operations ==============
1942
+ /**
1943
+ * List all database configurations in workspace
1944
+ */
1945
+ async listDatabases() {
1946
+ const headers = await this.getHeaders();
1947
+ const response = await listDatabases({
1948
+ client: this.client,
1949
+ headers
1950
+ });
1951
+ return extractData(response);
1952
+ }
1953
+ /**
1954
+ * Create a new database configuration
1955
+ */
1956
+ async createDatabase(config) {
1957
+ const headers = await this.getHeaders();
1958
+ const response = await createDatabase({
1959
+ client: this.client,
1960
+ body: config,
1961
+ headers
1962
+ });
1963
+ return extractData(response);
1964
+ }
1965
+ /**
1966
+ * Get database configuration by ID
1967
+ */
1968
+ async getDatabase(databaseId) {
1969
+ const headers = await this.getHeaders();
1970
+ const response = await getDatabase({
1971
+ client: this.client,
1972
+ path: { database_id: databaseId },
1973
+ headers
1974
+ });
1975
+ return extractData(response);
1976
+ }
1977
+ /**
1978
+ * Update database configuration
1979
+ */
1980
+ async updateDatabase(databaseId, updates) {
1981
+ const headers = await this.getHeaders();
1982
+ const response = await updateDatabase({
1983
+ client: this.client,
1984
+ path: { database_id: databaseId },
1985
+ body: updates,
1986
+ headers
1987
+ });
1988
+ return extractData(response);
1989
+ }
1990
+ /**
1991
+ * Delete database configuration
1992
+ */
1993
+ async deleteDatabase(databaseId) {
1994
+ const headers = await this.getHeaders();
1995
+ await deleteDatabase({
1996
+ client: this.client,
1997
+ path: { database_id: databaseId },
1998
+ headers
1999
+ });
2000
+ }
2001
+ /**
2002
+ * Test database connection
2003
+ */
2004
+ async testDatabaseConnection(databaseId) {
2005
+ const headers = await this.getHeaders();
2006
+ const response = await testDatabaseConnection({
2007
+ client: this.client,
2008
+ path: { database_id: databaseId },
2009
+ headers
2010
+ });
2011
+ return extractData(response);
2012
+ }
2013
+ /**
2014
+ * Get database schema (tables and columns)
2015
+ */
2016
+ async getDatabaseSchema(databaseId) {
2017
+ const headers = await this.getHeaders();
2018
+ const response = await getSchema({
2019
+ client: this.client,
2020
+ query: { database_id: databaseId },
2021
+ headers
2022
+ });
2023
+ return extractData(response);
2024
+ }
2025
+ /**
2026
+ * Get sample data from a table
2027
+ */
2028
+ async getDatabaseSample(tableName, databaseId, limit) {
2029
+ const headers = await this.getHeaders();
2030
+ const response = await getSample({
2031
+ client: this.client,
2032
+ path: { table_name: tableName },
2033
+ query: { database_id: databaseId, limit },
2034
+ headers
2035
+ });
2036
+ return extractData(response);
2037
+ }
2038
+ /**
2039
+ * List all tables in database
2040
+ */
2041
+ async listDatabaseTables(databaseId) {
2042
+ const headers = await this.getHeaders();
2043
+ const response = await listTables({
2044
+ client: this.client,
2045
+ query: { database_id: databaseId },
2046
+ headers
2047
+ });
2048
+ return extractData(response);
2049
+ }
2050
+ // ============== Project Operations ==============
2051
+ /**
2052
+ * List all projects in workspace
2053
+ */
2054
+ async listProjects(limit) {
2055
+ const headers = await this.getHeaders();
2056
+ const response = await listProjects({
2057
+ client: this.client,
2058
+ query: { limit },
2059
+ headers
2060
+ });
2061
+ return extractData(response);
2062
+ }
2063
+ /**
2064
+ * Create a new project with auto-generated UUID
2065
+ */
2066
+ async createProject(name, description) {
2067
+ const headers = await this.getHeaders();
2068
+ const body = {
2069
+ name,
2070
+ description
2071
+ };
2072
+ const response = await createProject({
2073
+ client: this.client,
2074
+ body,
2075
+ headers
2076
+ });
2077
+ return extractData(response);
2078
+ }
2079
+ /**
2080
+ * Get project by ID
2081
+ */
2082
+ async getProject(projectId) {
2083
+ const headers = await this.getHeaders();
2084
+ const response = await getProject({
2085
+ client: this.client,
2086
+ path: { project_id: projectId },
2087
+ headers
2088
+ });
2089
+ return extractData(response);
2090
+ }
2091
+ /**
2092
+ * Update project
2093
+ */
2094
+ async updateProject(projectId, updates) {
2095
+ const headers = await this.getHeaders();
2096
+ const response = await updateProject({
2097
+ client: this.client,
2098
+ path: { project_id: projectId },
2099
+ body: updates,
2100
+ headers
2101
+ });
2102
+ return extractData(response);
2103
+ }
2104
+ /**
2105
+ * Delete project
2106
+ */
2107
+ async deleteProject(projectId) {
2108
+ const headers = await this.getHeaders();
2109
+ await deleteProject({
2110
+ client: this.client,
2111
+ path: { project_id: projectId },
2112
+ headers
2113
+ });
2114
+ }
2115
+ /**
2116
+ * Add repository to project
2117
+ */
2118
+ async addProjectRepo(projectId, repoId, options) {
2119
+ const headers = await this.getHeaders();
2120
+ const body = {
2121
+ repo_id: repoId,
2122
+ category: options?.category,
2123
+ priority: options?.priority,
2124
+ auto_include: options?.autoInclude,
2125
+ branch: options?.branch
2126
+ };
2127
+ const response = await addLinkedRepo({
2128
+ client: this.client,
2129
+ path: { project_id: projectId },
2130
+ body,
2131
+ headers
2132
+ });
2133
+ return extractData(response);
2134
+ }
2135
+ /**
2136
+ * Remove repository from project
2137
+ */
2138
+ async removeProjectRepo(projectId, repoId) {
2139
+ const headers = await this.getHeaders();
2140
+ const response = await removeLinkedRepo({
2141
+ client: this.client,
2142
+ path: { project_id: projectId, repo_id: repoId },
2143
+ headers
2144
+ });
2145
+ return extractData(response);
2146
+ }
2147
+ /**
2148
+ * Set default repository for project
2149
+ */
2150
+ async setDefaultRepo(projectId, repoId) {
2151
+ const headers = await this.getHeaders();
2152
+ const body = { repo_id: repoId };
2153
+ const response = await setDefaultRepo({
2154
+ client: this.client,
2155
+ path: { project_id: projectId },
2156
+ body,
2157
+ headers
2158
+ });
2159
+ return extractData(response);
2160
+ }
2161
+ /**
2162
+ * Get context repositories for project (auto-include enabled)
2163
+ */
2164
+ async getContextRepos(projectId) {
2165
+ const headers = await this.getHeaders();
2166
+ const response = await getContextRepos({
2167
+ client: this.client,
2168
+ path: { project_id: projectId },
2169
+ headers
2170
+ });
2171
+ const data = extractData(response);
2172
+ return data.repos || [];
2173
+ }
2174
+ /**
2175
+ * Add mission to project
2176
+ */
2177
+ async addProjectMission(projectId, missionId) {
2178
+ const headers = await this.getHeaders();
2179
+ const body = { mission_id: missionId };
2180
+ const response = await addMission({
2181
+ client: this.client,
2182
+ path: { project_id: projectId },
2183
+ body,
2184
+ headers
2185
+ });
2186
+ return extractData(response);
2187
+ }
2188
+ /**
2189
+ * Remove mission from project
2190
+ */
2191
+ async removeProjectMission(projectId, missionId) {
2192
+ const headers = await this.getHeaders();
2193
+ const response = await removeMission({
2194
+ client: this.client,
2195
+ path: { project_id: projectId, mission_id: missionId },
2196
+ headers
2197
+ });
2198
+ return extractData(response);
2199
+ }
2200
+ // ============== Session Operations ==============
2201
+ /**
2202
+ * List all sessions in workspace
2203
+ */
2204
+ async listSessions(limit, status) {
2205
+ const headers = await this.getHeaders();
2206
+ const response = await listSessions({
2207
+ client: this.client,
2208
+ query: { limit, status },
2209
+ headers
2210
+ });
2211
+ return extractData(response);
2212
+ }
2213
+ /**
2214
+ * Get session messages
2215
+ */
2216
+ async getSessionMessages(sessionId, limit) {
2217
+ const headers = await this.getHeaders();
2218
+ const response = await getSessionMessages({
2219
+ client: this.client,
2220
+ path: { session_id: sessionId },
2221
+ query: { limit },
2222
+ headers
2223
+ });
2224
+ return extractData(response);
2225
+ }
2226
+ /**
2227
+ * Update session metadata
2228
+ */
2229
+ async updateSessionMetadata(sessionId, updates) {
2230
+ const headers = await this.getHeaders();
2231
+ const response = await updateSessionMetadata({
2232
+ client: this.client,
2233
+ path: { session_id: sessionId },
2234
+ body: updates,
2235
+ headers
2236
+ });
2237
+ return extractData(response);
2238
+ }
2239
+ /**
2240
+ * Fork session
2241
+ */
2242
+ async forkSession(sessionId, missionId, forkPoint) {
2243
+ const headers = await this.getHeaders();
2244
+ const body = { mission_id: missionId, fork_point: forkPoint };
2245
+ const response = await forkSession({
2246
+ client: this.client,
2247
+ path: { session_id: sessionId },
2248
+ body,
2249
+ headers
2250
+ });
2251
+ return extractData(response);
2252
+ }
2253
+ /**
2254
+ * Archive session
2255
+ */
2256
+ async archiveSession(sessionId) {
2257
+ const headers = await this.getHeaders();
2258
+ await archiveSession({
2259
+ client: this.client,
2260
+ path: { session_id: sessionId },
2261
+ headers
2262
+ });
2263
+ }
2264
+ // ============== Auth Operations ==============
2265
+ /**
2266
+ * Get auth configuration (public endpoint)
2267
+ */
2268
+ async getAuthConfig() {
2269
+ const response = await getAuthConfig({
2270
+ client: this.client
2271
+ });
2272
+ return extractData(response);
2273
+ }
2274
+ /**
2275
+ * Get current authenticated user
2276
+ */
2277
+ async getCurrentUser() {
2278
+ const headers = await this.getHeaders();
2279
+ const response = await getCurrentUser({
2280
+ client: this.client,
2281
+ headers
2282
+ });
2283
+ return extractData(response);
2284
+ }
2285
+ /**
2286
+ * List workspaces for authenticated user
2287
+ */
2288
+ async listWorkspaces() {
2289
+ const headers = await this.getHeaders();
2290
+ const response = await listWorkspaces({
2291
+ client: this.client,
2292
+ headers
2293
+ });
2294
+ return extractData(response);
2295
+ }
2296
+ /**
2297
+ * Login with username and password (JSON endpoint for programmatic clients)
2298
+ * @param username - Cognito username
2299
+ * @param password - User password
2300
+ * @returns Token response with access_token, refresh_token, and expires_in
2301
+ */
2302
+ async login(username, password) {
2303
+ const response = await login({
2304
+ client: this.client,
2305
+ body: { username, password }
2306
+ });
2307
+ return extractData(response);
2308
+ }
2309
+ /**
2310
+ * Refresh access token using refresh token
2311
+ * @param refreshToken - The refresh token from login
2312
+ * @returns New access token (refresh token remains the same)
2313
+ */
2314
+ async refreshToken(refreshToken) {
2315
+ const response = await refreshTokens({
2316
+ client: this.client,
2317
+ body: { refreshToken }
2318
+ });
2319
+ return extractData(response);
2320
+ }
2321
+ /**
2322
+ * Set GitHub token for the authenticated user
2323
+ * Stores the token server-side linked to the Cognito identity
2324
+ * @param token - GitHub Personal Access Token
2325
+ * @returns Success response
2326
+ */
2327
+ async setGitHubToken(token) {
2328
+ const headers = await this.getHeaders();
2329
+ const response = await this.client.request({
2330
+ method: "PUT",
2331
+ url: "/auth/github-token",
2332
+ headers,
2333
+ body: { github_token: token }
2334
+ });
2335
+ if (response.error) {
2336
+ throw new Error(`Failed to set GitHub token: ${typeof response.error === "object" ? JSON.stringify(response.error) : response.error}`);
2337
+ }
2338
+ if (response.data === true) {
2339
+ return { success: true };
2340
+ }
2341
+ return response.data || { success: true };
2342
+ }
2343
+ /**
2344
+ * Get GitHub token status for the authenticated user
2345
+ * @returns Token status (configured or not)
2346
+ */
2347
+ async getGitHubTokenStatus() {
2348
+ const headers = await this.getHeaders();
2349
+ const response = await this.client.request({
2350
+ method: "GET",
2351
+ url: "/auth/github-token",
2352
+ headers
2353
+ });
2354
+ if (response.error) {
2355
+ throw new Error(`Failed to get GitHub token status: ${typeof response.error === "object" ? JSON.stringify(response.error) : response.error}`);
2356
+ }
2357
+ const data = response.data;
2358
+ if (data && typeof data === "object" && "configured" in data) {
2359
+ return data;
2360
+ }
2361
+ return { configured: false };
2362
+ }
2363
+ /**
2364
+ * Delete GitHub token for the authenticated user
2365
+ * @returns Success response
2366
+ */
2367
+ async deleteGitHubToken() {
2368
+ const headers = await this.getHeaders();
2369
+ const response = await this.client.request({
2370
+ method: "DELETE",
2371
+ url: "/auth/github-token",
2372
+ headers
2373
+ });
2374
+ if (response.error) {
2375
+ throw new Error(`Failed to delete GitHub token: ${typeof response.error === "object" ? JSON.stringify(response.error) : response.error}`);
2376
+ }
2377
+ if (response.data === true) {
2378
+ return { success: true };
2379
+ }
2380
+ return response.data || { success: true };
2381
+ }
2382
+ // ============== Namespaced Accessors ==============
2383
+ _mission;
2384
+ _project;
2385
+ _session;
2386
+ _kb;
2387
+ /**
2388
+ * Mission namespace for convenient mission operations
2389
+ * @example ocxp.mission.list({ status: 'pending' })
2390
+ */
2391
+ get mission() {
2392
+ if (!this._mission) {
2393
+ this._mission = new MissionNamespace(this);
2394
+ }
2395
+ return this._mission;
2396
+ }
2397
+ /**
2398
+ * Project namespace for convenient project operations
2399
+ * @example ocxp.project.list()
2400
+ */
2401
+ get project() {
2402
+ if (!this._project) {
2403
+ this._project = new ProjectNamespace(this);
2404
+ }
2405
+ return this._project;
2406
+ }
2407
+ /**
2408
+ * Session namespace for convenient session operations
2409
+ * @example ocxp.session.list({ status: 'active' })
2410
+ */
2411
+ get session() {
2412
+ if (!this._session) {
2413
+ this._session = new SessionNamespace(this);
2414
+ }
2415
+ return this._session;
2416
+ }
2417
+ /**
2418
+ * KB namespace for convenient knowledge base operations
2419
+ * @example ocxp.kb.query('search term')
2420
+ */
2421
+ get kb() {
2422
+ if (!this._kb) {
2423
+ this._kb = new KBNamespace(this);
2424
+ }
2425
+ return this._kb;
2426
+ }
2427
+ };
2428
+ var MissionNamespace = class {
2429
+ constructor(client2) {
2430
+ this.client = client2;
2431
+ }
2432
+ /**
2433
+ * List missions with optional filtering
2434
+ * @example ocxp.mission.list({ status: 'active', limit: 10 })
2435
+ */
2436
+ async list(options) {
2437
+ return this.client.listMissions(options);
2438
+ }
2439
+ /**
2440
+ * Get a mission by ID
2441
+ * @example ocxp.mission.get('uuid')
2442
+ */
2443
+ async get(missionId) {
2444
+ return this.client.getMission(missionId);
2445
+ }
2446
+ /**
2447
+ * Create a new mission with auto-generated UUID
2448
+ * @example ocxp.mission.create({ title: 'My Mission', description: 'Description' })
2449
+ */
2450
+ async create(data) {
2451
+ return this.client.createMission(data.title, data.description, data.projectId, data.goals);
2452
+ }
2453
+ /**
2454
+ * Update mission
2455
+ */
2456
+ async update(missionId, updates) {
2457
+ return this.client.updateMission(missionId, updates);
2458
+ }
2459
+ /**
2460
+ * Delete mission
2461
+ */
2462
+ async delete(missionId) {
2463
+ return this.client.deleteMission(missionId);
2464
+ }
2465
+ /**
2466
+ * Add session to mission
2467
+ */
2468
+ async addSession(missionId, sessionId) {
2469
+ return this.client.addMissionSession(missionId, sessionId);
2470
+ }
2471
+ /**
2472
+ * Remove session from mission
2473
+ */
2474
+ async removeSession(missionId, sessionId) {
2475
+ return this.client.removeMissionSession(missionId, sessionId);
2476
+ }
2477
+ /**
2478
+ * Regenerate mission - archives old docs and triggers AgentCore
2479
+ * @example ocxp.mission.regenerate('uuid', { ticket_id: 'AMC-123' })
2480
+ */
2481
+ async regenerate(missionId, options) {
2482
+ return this.client.regenerateMission(missionId, options);
2483
+ }
2484
+ /**
2485
+ * Download mission pack as ZIP
2486
+ * @example await ocxp.mission.download('mission-id')
2487
+ */
2488
+ async download(missionId) {
2489
+ return this.client.downloadMissionPack(missionId);
2490
+ }
2491
+ /**
2492
+ * Get mission context for agents
2493
+ * @example ocxp.mission.getContext('uuid')
2494
+ */
2495
+ async getContext(missionId) {
2496
+ return this.client.getMissionContext(missionId);
2497
+ }
2498
+ /**
2499
+ * Get mission content tree structure from S3
2500
+ * @example ocxp.mission.tree('subfolder', 5)
2501
+ */
2502
+ async tree(path, depth) {
2503
+ return this.client.tree("mission", path, depth);
2504
+ }
2505
+ };
2506
+ var ProjectNamespace = class {
2507
+ constructor(client2) {
2508
+ this.client = client2;
2509
+ }
2510
+ /**
2511
+ * List all projects
2512
+ * @example ocxp.project.list()
2513
+ */
2514
+ async list(limit) {
2515
+ return this.client.listProjects(limit);
2516
+ }
2517
+ /**
2518
+ * Get a project by ID
2519
+ * @example ocxp.project.get('my-project')
2520
+ */
2521
+ async get(projectId) {
2522
+ return this.client.getProject(projectId);
2523
+ }
2524
+ /**
2525
+ * Create a new project with auto-generated UUID
2526
+ * @example ocxp.project.create({ name: 'My Project', description: 'Optional description' })
2527
+ */
2528
+ async create(data) {
2529
+ return this.client.createProject(data.name, data.description);
2530
+ }
2531
+ /**
2532
+ * Update a project
2533
+ */
2534
+ async update(projectId, data) {
2535
+ return this.client.updateProject(projectId, data);
2536
+ }
2537
+ /**
2538
+ * Delete a project
2539
+ */
2540
+ async delete(projectId) {
2541
+ return this.client.deleteProject(projectId);
2542
+ }
2543
+ /**
2544
+ * Add a repository to a project
2545
+ */
2546
+ async addRepo(projectId, repoId, options) {
2547
+ return this.client.addProjectRepo(projectId, repoId, options);
2548
+ }
2549
+ /**
2550
+ * Remove a repository from a project
2551
+ */
2552
+ async removeRepo(projectId, repoId) {
2553
+ return this.client.removeProjectRepo(projectId, repoId);
2554
+ }
2555
+ /**
2556
+ * Set the default repository for a project
2557
+ */
2558
+ async setDefaultRepo(projectId, repoId) {
2559
+ return this.client.setDefaultRepo(projectId, repoId);
2560
+ }
2561
+ /**
2562
+ * Get context repositories for a project
2563
+ */
2564
+ async getContextRepos(projectId) {
2565
+ return this.client.getContextRepos(projectId);
2566
+ }
2567
+ /**
2568
+ * Add a mission to a project
2569
+ */
2570
+ async addMission(projectId, missionId) {
2571
+ return this.client.addProjectMission(projectId, missionId);
2572
+ }
2573
+ /**
2574
+ * Remove a mission from a project
2575
+ */
2576
+ async removeMission(projectId, missionId) {
2577
+ return this.client.removeProjectMission(projectId, missionId);
2578
+ }
2579
+ /**
2580
+ * Get project content tree structure from S3
2581
+ * @example ocxp.project.tree('subfolder', 5)
2582
+ */
2583
+ async tree(path, depth) {
2584
+ return this.client.tree("project", path, depth);
2585
+ }
2586
+ };
2587
+ var SessionNamespace = class {
2588
+ constructor(client2) {
2589
+ this.client = client2;
2590
+ }
2591
+ /**
2592
+ * List sessions with optional filtering
2593
+ * @example ocxp.session.list({ status: 'active', limit: 10 })
2594
+ */
2595
+ async list(options) {
2596
+ return this.client.listSessions(options?.limit, options?.status);
2597
+ }
2598
+ /**
2599
+ * Get session messages
2600
+ * @example ocxp.session.getMessages('session-id')
2601
+ */
2602
+ async getMessages(sessionId) {
2603
+ return this.client.getSessionMessages(sessionId);
2604
+ }
2605
+ /**
2606
+ * Update session metadata
2607
+ */
2608
+ async updateMetadata(sessionId, data) {
2609
+ return this.client.updateSessionMetadata(sessionId, data);
2610
+ }
2611
+ /**
2612
+ * Fork a session
2613
+ */
2614
+ async fork(sessionId, missionId, forkPoint) {
2615
+ return this.client.forkSession(sessionId, missionId, forkPoint);
2616
+ }
2617
+ /**
2618
+ * Archive a session
2619
+ */
2620
+ async archive(sessionId) {
2621
+ return this.client.archiveSession(sessionId);
2622
+ }
2623
+ };
2624
+ var KBNamespace = class {
2625
+ constructor(client2) {
2626
+ this.client = client2;
2627
+ }
2628
+ /**
2629
+ * Query the knowledge base with optional filtering and external docs fallback
2630
+ * @example ocxp.kb.query('search term', { searchType: 'HYBRID', maxResults: 10 })
2631
+ * @example ocxp.kb.query('authentication', { projectId: 'my-project', missionId: 'CTX-123' })
2632
+ * @example ocxp.kb.query('strands agent', { enableFallback: true, persistExternalDocs: true })
2633
+ */
2634
+ async query(query, options) {
2635
+ return this.client.kbQuery(query, options);
2636
+ }
2637
+ /**
2638
+ * RAG query with LLM response and citations
2639
+ * @example ocxp.kb.rag('What is OCXP?')
2640
+ */
2641
+ async rag(query, sessionId) {
2642
+ return this.client.kbRag(query, sessionId);
2643
+ }
2644
+ };
2645
+ function createOCXPClient(options) {
2646
+ return new OCXPClient(options);
2647
+ }
2648
+
2649
+ // src/path.ts
2650
+ var VALID_CONTENT_TYPES = [
2651
+ "mission",
2652
+ "project",
2653
+ "context",
2654
+ "sop",
2655
+ "repo",
2656
+ "artifact",
2657
+ "kb",
2658
+ "docs"
2659
+ ];
2660
+ var TYPE_ALIASES = {
2661
+ mission: "mission",
2662
+ missions: "mission",
2663
+ project: "project",
2664
+ projects: "project",
2665
+ context: "context",
2666
+ contexts: "context",
2667
+ sop: "sop",
2668
+ sops: "sop",
2669
+ repo: "repo",
2670
+ repos: "repo",
2671
+ artifact: "artifact",
2672
+ artifacts: "artifact",
2673
+ kb: "kb",
2674
+ kbs: "kb",
2675
+ docs: "docs"
2676
+ };
2677
+ function parsePath(path) {
2678
+ const normalized = path.replace(/^\/+/, "").replace(/\/+$/, "");
2679
+ const parts = normalized.split("/");
2680
+ if (parts.length === 0 || !parts[0]) {
2681
+ throw new Error(`Invalid path: ${path}`);
2682
+ }
2683
+ const typeKey = parts[0].toLowerCase();
2684
+ const type = TYPE_ALIASES[typeKey];
2685
+ if (!type) {
2686
+ throw new Error(
2687
+ `Invalid content type: ${parts[0]}. Valid types: ${VALID_CONTENT_TYPES.join(", ")}`
2688
+ );
2689
+ }
2690
+ const id = parts.length > 1 ? parts.slice(1).join("/") : void 0;
2691
+ return { type, id };
2692
+ }
2693
+ function normalizePath(path) {
2694
+ return path.replace(/^missions\//, "mission/").replace(/^projects\//, "project/").replace(/^contexts\//, "context/").replace(/^sops\//, "sop/").replace(/^repos\//, "repo/").replace(/^artifacts\//, "artifact/").replace(/^kbs\//, "kb/");
2695
+ }
2696
+ function isValidContentType(type) {
2697
+ return VALID_CONTENT_TYPES.includes(type);
2698
+ }
2699
+ function getCanonicalType(type) {
2700
+ return TYPE_ALIASES[type.toLowerCase()];
2701
+ }
2702
+ function buildPath(type, id) {
2703
+ if (id) {
2704
+ return `${type}/${id}`;
2705
+ }
2706
+ return `${type}/`;
2707
+ }
2708
+
2709
+ // src/path-service.ts
2710
+ var OCXPPathService = class {
2711
+ client;
2712
+ endpoint;
2713
+ workspace;
2714
+ constructor(options) {
2715
+ this.endpoint = options.endpoint;
2716
+ this.workspace = options.workspace || "dev";
2717
+ this.client = new OCXPClient({
2718
+ endpoint: options.endpoint,
2719
+ workspace: this.workspace,
2720
+ token: options.token
2721
+ });
2722
+ }
2723
+ // ===========================================================================
2724
+ // Read Operations
2725
+ // ===========================================================================
2726
+ /**
2727
+ * List directory contents
2728
+ *
2729
+ * @param path - Path like 'mission/' or 'project/'
2730
+ * @param limit - Maximum entries to return
2731
+ * @returns List result with entries
2732
+ */
2733
+ async list(path, limit) {
2734
+ const { type, id } = parsePath(path);
2735
+ const result = await this.client.list(type, id, limit);
2736
+ return {
2737
+ path,
2738
+ entries: result.entries.map(
2739
+ (entry) => ({
2740
+ name: entry.name ?? "",
2741
+ path: normalizePath(entry.path ?? ""),
2742
+ type: entry.type ?? "file",
2743
+ size: entry.size,
2744
+ mtime: entry.mtime
2745
+ })
2746
+ ),
2747
+ cursor: result.cursor,
2748
+ hasMore: result.hasMore,
2749
+ total: result.total
2750
+ };
2751
+ }
2752
+ /**
2753
+ * Read file content
2754
+ *
2755
+ * @param path - Path like 'mission/CTX-123/PHASES.md'
2756
+ * @returns Read result with content
2757
+ */
2758
+ async read(path) {
2759
+ const { type, id } = parsePath(path);
2760
+ if (!id) {
2761
+ throw new Error(`Cannot read directory path: ${path}`);
2762
+ }
2763
+ const result = await this.client.read(type, id);
2764
+ return {
2765
+ path,
2766
+ type: "text",
2767
+ content: result.content,
2768
+ encoding: result.encoding ?? "utf-8",
2769
+ info: {
2770
+ path,
2771
+ size: result.size,
2772
+ mtime: result.mtime
2773
+ }
2774
+ };
2775
+ }
2776
+ /**
2777
+ * Check if path exists
2778
+ *
2779
+ * @param path - Path to check
2780
+ * @returns true if exists
2781
+ */
2782
+ async exists(path) {
2783
+ try {
2784
+ const { type, id } = parsePath(path);
2785
+ if (!id) {
2786
+ await this.client.list(type);
2787
+ return true;
2788
+ }
2789
+ await this.client.read(type, id);
2790
+ return true;
2791
+ } catch {
2792
+ return false;
2793
+ }
2794
+ }
2795
+ /**
2796
+ * Get file metadata
2797
+ *
2798
+ * @param path - Path to get info for
2799
+ * @returns File info
2800
+ */
2801
+ async info(path) {
2802
+ const { type, id } = parsePath(path);
2803
+ const result = await this.client.stats(type, id);
2804
+ const data = result?.data || {};
2805
+ return {
2806
+ path,
2807
+ size: data.size,
2808
+ mtime: data.mtime,
2809
+ hash: data.hash,
2810
+ contentType: data.contentType
2811
+ };
2812
+ }
2813
+ // ===========================================================================
2814
+ // Write Operations
2815
+ // ===========================================================================
2816
+ /**
2817
+ * Write/update file content
2818
+ *
2819
+ * @param path - Path like 'mission/CTX-123/PHASES.md'
2820
+ * @param content - File content
2821
+ * @param options - Write options
2822
+ * @returns Write result
2823
+ */
2824
+ async write(path, content, options) {
2825
+ const { type, id } = parsePath(path);
2826
+ if (!id) {
2827
+ throw new Error(`Cannot write to directory path: ${path}`);
2828
+ }
2829
+ await this.client.write(type, id, content, {
2830
+ encoding: options?.encoding,
2831
+ ifNotExists: options?.ifNotExists,
2832
+ etag: options?.etag
2833
+ });
2834
+ return {
2835
+ success: true,
2836
+ path
2837
+ };
2838
+ }
2839
+ /**
2840
+ * Delete a file
2841
+ *
2842
+ * @param path - Path like 'mission/CTX-123/PHASES.md'
2843
+ * @returns Write result
2844
+ */
2845
+ async delete(path) {
2846
+ const { type, id } = parsePath(path);
2847
+ if (!id) {
2848
+ throw new Error(`Cannot delete directory path without id: ${path}`);
2849
+ }
2850
+ await this.client.delete(type, id);
2851
+ return {
2852
+ success: true,
2853
+ path
2854
+ };
2855
+ }
2856
+ /**
2857
+ * Move/rename a file
2858
+ *
2859
+ * Implemented as read + write + delete
2860
+ *
2861
+ * @param sourcePath - Source path
2862
+ * @param destPath - Destination path
2863
+ * @returns Move result
2864
+ */
2865
+ async move(sourcePath, destPath) {
2866
+ const content = await this.read(sourcePath);
2867
+ await this.write(destPath, content.content);
2868
+ await this.delete(sourcePath);
2869
+ return {
2870
+ success: true,
2871
+ sourcePath,
2872
+ destPath
2873
+ };
2874
+ }
2875
+ // ===========================================================================
2876
+ // Utility Methods
2877
+ // ===========================================================================
2878
+ /**
2879
+ * Get the underlying OCXPClient
2880
+ */
2881
+ getClient() {
2882
+ return this.client;
2883
+ }
2884
+ /**
2885
+ * Get the API endpoint
2886
+ */
2887
+ getEndpoint() {
2888
+ return this.endpoint;
2889
+ }
2890
+ /**
2891
+ * Get the workspace ID
2892
+ */
2893
+ getWorkspace() {
2894
+ return this.workspace;
2895
+ }
2896
+ /**
2897
+ * Update the workspace
2898
+ */
2899
+ setWorkspace(workspace) {
2900
+ this.client.setWorkspace(workspace);
2901
+ }
2902
+ /**
2903
+ * Update the auth token
2904
+ */
2905
+ setToken(token) {
2906
+ this.client.setToken(token);
2907
+ }
2908
+ };
2909
+ function createPathService(options) {
2910
+ return new OCXPPathService(options);
2911
+ }
2912
+
2913
+ // src/websocket.ts
2914
+ var WebSocketService = class {
2915
+ constructor(options) {
2916
+ this.options = options;
2917
+ }
2918
+ ws = null;
2919
+ reconnectAttempts = 0;
2920
+ reconnectTimeout = null;
2921
+ eventHandlers = /* @__PURE__ */ new Map();
2922
+ connectionStateHandlers = /* @__PURE__ */ new Set();
2923
+ connectionPromise = null;
2924
+ _connectionState = "disconnected";
2925
+ shouldReconnect = true;
2926
+ /**
2927
+ * Get current connection state
2928
+ */
2929
+ get connectionState() {
2930
+ return this._connectionState;
2931
+ }
2932
+ /**
2933
+ * Check if connected
2934
+ */
2935
+ get connected() {
2936
+ return this.ws?.readyState === WebSocket.OPEN;
2937
+ }
2938
+ /**
2939
+ * Connect to WebSocket server
2940
+ */
2941
+ async connect() {
2942
+ if (this.connectionPromise) return this.connectionPromise;
2943
+ if (this.connected) return Promise.resolve();
2944
+ this.shouldReconnect = true;
2945
+ this.connectionPromise = this.doConnect();
2946
+ return this.connectionPromise;
2947
+ }
2948
+ setConnectionState(state) {
2949
+ this._connectionState = state;
2950
+ this.connectionStateHandlers.forEach((handler) => handler(state));
2951
+ }
2952
+ async doConnect() {
2953
+ this.setConnectionState("connecting");
2954
+ const token = typeof this.options.token === "function" ? await this.options.token() : this.options.token;
2955
+ const params = new URLSearchParams({
2956
+ workspace: this.options.workspace
2957
+ });
2958
+ if (this.options.userId) {
2959
+ params.set("user_id", this.options.userId);
2960
+ }
2961
+ if (token) {
2962
+ params.set("token", token);
2963
+ }
2964
+ const url = `${this.options.endpoint}?${params}`;
2965
+ return new Promise((resolve, reject) => {
2966
+ const timeout = setTimeout(() => {
2967
+ this.ws?.close();
2968
+ reject(new Error("WebSocket connection timeout"));
2969
+ }, this.options.connectionTimeoutMs ?? 1e4);
2970
+ try {
2971
+ this.ws = new WebSocket(url);
2972
+ } catch (error) {
2973
+ clearTimeout(timeout);
2974
+ this.connectionPromise = null;
2975
+ this.setConnectionState("disconnected");
2976
+ reject(error instanceof Error ? error : new Error(String(error)));
2977
+ return;
2978
+ }
2979
+ this.ws.onopen = () => {
2980
+ clearTimeout(timeout);
2981
+ this.reconnectAttempts = 0;
2982
+ this.setConnectionState("connected");
2983
+ resolve();
2984
+ };
2985
+ this.ws.onmessage = (event) => {
2986
+ try {
2987
+ const message = JSON.parse(event.data);
2988
+ this.dispatchMessage(message);
2989
+ } catch {
2990
+ }
2991
+ };
2992
+ this.ws.onclose = (event) => {
2993
+ clearTimeout(timeout);
2994
+ this.connectionPromise = null;
2995
+ if (this.shouldReconnect && event.code !== 1e3) {
2996
+ this.setConnectionState("reconnecting");
2997
+ this.handleReconnect();
2998
+ } else {
2999
+ this.setConnectionState("disconnected");
3000
+ }
3001
+ };
3002
+ this.ws.onerror = () => {
3003
+ clearTimeout(timeout);
3004
+ this.connectionPromise = null;
3005
+ reject(new Error("WebSocket connection failed"));
3006
+ };
3007
+ });
3008
+ }
3009
+ handleReconnect() {
3010
+ if (!this.shouldReconnect) return;
3011
+ const maxAttempts = this.options.maxReconnectAttempts ?? 5;
3012
+ if (this.reconnectAttempts >= maxAttempts) {
3013
+ this.setConnectionState("disconnected");
3014
+ return;
3015
+ }
3016
+ const delay = (this.options.reconnectDelayMs ?? 1e3) * Math.pow(2, this.reconnectAttempts);
3017
+ this.reconnectAttempts++;
3018
+ this.reconnectTimeout = setTimeout(() => {
3019
+ this.connect().catch(() => {
3020
+ });
3021
+ }, delay);
3022
+ }
3023
+ dispatchMessage(message) {
3024
+ const handlers = this.eventHandlers.get(message.type);
3025
+ handlers?.forEach((handler) => handler(message));
3026
+ const wildcardHandlers = this.eventHandlers.get("*");
3027
+ wildcardHandlers?.forEach((handler) => handler(message));
3028
+ }
3029
+ /**
3030
+ * Subscribe to message types
3031
+ * @returns Unsubscribe function
3032
+ */
3033
+ on(type, handler) {
3034
+ if (!this.eventHandlers.has(type)) {
3035
+ this.eventHandlers.set(type, /* @__PURE__ */ new Set());
3036
+ }
3037
+ this.eventHandlers.get(type).add(handler);
3038
+ return () => this.eventHandlers.get(type)?.delete(handler);
3039
+ }
3040
+ /**
3041
+ * Subscribe to job progress updates
3042
+ */
3043
+ onJobProgress(handler) {
3044
+ return this.on("job_progress", handler);
3045
+ }
3046
+ /**
3047
+ * Subscribe to repository status updates
3048
+ */
3049
+ onRepoStatus(handler) {
3050
+ return this.on("repo_status", handler);
3051
+ }
3052
+ /**
3053
+ * Subscribe to notifications
3054
+ */
3055
+ onNotification(handler) {
3056
+ return this.on("notification", handler);
3057
+ }
3058
+ /**
3059
+ * Subscribe to sync events
3060
+ */
3061
+ onSyncEvent(handler) {
3062
+ return this.on("sync_event", handler);
3063
+ }
3064
+ /**
3065
+ * Subscribe to connection state changes
3066
+ */
3067
+ onConnectionStateChange(handler) {
3068
+ this.connectionStateHandlers.add(handler);
3069
+ return () => this.connectionStateHandlers.delete(handler);
3070
+ }
3071
+ /**
3072
+ * Subscribe to specific job updates
3073
+ */
3074
+ subscribeToJob(jobId) {
3075
+ this.send({ action: "subscribe", type: "job", id: jobId });
3076
+ }
3077
+ /**
3078
+ * Subscribe to repository updates
3079
+ */
3080
+ subscribeToRepo(repoId) {
3081
+ this.send({ action: "subscribe", type: "repo", id: repoId });
3082
+ }
3083
+ /**
3084
+ * Send message to server
3085
+ */
3086
+ send(data) {
3087
+ if (this.ws?.readyState === WebSocket.OPEN) {
3088
+ this.ws.send(JSON.stringify(data));
3089
+ }
3090
+ }
3091
+ /**
3092
+ * Send ping to keep connection alive
3093
+ */
3094
+ ping() {
3095
+ this.send({ action: "ping" });
3096
+ }
3097
+ /**
3098
+ * Disconnect and cleanup
3099
+ */
3100
+ disconnect() {
3101
+ this.shouldReconnect = false;
3102
+ if (this.reconnectTimeout) {
3103
+ clearTimeout(this.reconnectTimeout);
3104
+ this.reconnectTimeout = null;
3105
+ }
3106
+ if (this.ws) {
3107
+ this.ws.close(1e3, "Client disconnect");
3108
+ this.ws = null;
3109
+ }
3110
+ this.connectionPromise = null;
3111
+ this.reconnectAttempts = 0;
3112
+ this.setConnectionState("disconnected");
3113
+ }
3114
+ /**
3115
+ * Clear all event handlers
3116
+ */
3117
+ clearHandlers() {
3118
+ this.eventHandlers.clear();
3119
+ this.connectionStateHandlers.clear();
3120
+ }
3121
+ };
3122
+ function createWebSocketService(options) {
3123
+ return new WebSocketService(options);
3124
+ }
3125
+
3126
+ // src/types/errors.ts
3127
+ var OCXPErrorCode = /* @__PURE__ */ ((OCXPErrorCode2) => {
3128
+ OCXPErrorCode2["NETWORK_ERROR"] = "NETWORK_ERROR";
3129
+ OCXPErrorCode2["VALIDATION_ERROR"] = "VALIDATION_ERROR";
3130
+ OCXPErrorCode2["AUTH_ERROR"] = "AUTH_ERROR";
3131
+ OCXPErrorCode2["NOT_FOUND"] = "NOT_FOUND";
3132
+ OCXPErrorCode2["RATE_LIMITED"] = "RATE_LIMITED";
3133
+ OCXPErrorCode2["CONFLICT"] = "CONFLICT";
3134
+ OCXPErrorCode2["TIMEOUT"] = "TIMEOUT";
3135
+ OCXPErrorCode2["SERVER_ERROR"] = "SERVER_ERROR";
3136
+ OCXPErrorCode2["UNKNOWN"] = "UNKNOWN";
3137
+ return OCXPErrorCode2;
3138
+ })(OCXPErrorCode || {});
3139
+ var OCXPError = class extends Error {
3140
+ /** Error code for programmatic handling */
3141
+ code;
3142
+ /** HTTP status code if applicable */
3143
+ statusCode;
3144
+ /** Additional error details */
3145
+ details;
3146
+ /** Request ID for debugging */
3147
+ requestId;
3148
+ /** Original cause of the error */
3149
+ cause;
3150
+ constructor(message, code = "UNKNOWN" /* UNKNOWN */, statusCode = 500, options) {
3151
+ super(message);
3152
+ this.name = "OCXPError";
3153
+ this.code = code;
3154
+ this.statusCode = statusCode;
3155
+ this.details = options?.details;
3156
+ this.requestId = options?.requestId;
3157
+ this.cause = options?.cause;
3158
+ if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
3159
+ Error.captureStackTrace(this, this.constructor);
3160
+ }
3161
+ }
3162
+ /**
3163
+ * Convert error to JSON for logging/serialization
3164
+ */
3165
+ toJSON() {
3166
+ return {
3167
+ name: this.name,
3168
+ message: this.message,
3169
+ code: this.code,
3170
+ statusCode: this.statusCode,
3171
+ details: this.details,
3172
+ requestId: this.requestId,
3173
+ stack: this.stack
3174
+ };
3175
+ }
3176
+ };
3177
+ var OCXPNetworkError = class extends OCXPError {
3178
+ constructor(message, options) {
3179
+ super(message, "NETWORK_ERROR" /* NETWORK_ERROR */, 0, options);
3180
+ this.name = "OCXPNetworkError";
3181
+ }
3182
+ };
3183
+ var OCXPValidationError = class extends OCXPError {
3184
+ /** Field-level validation errors */
3185
+ validationErrors;
3186
+ constructor(message, validationErrors, options) {
3187
+ super(message, "VALIDATION_ERROR" /* VALIDATION_ERROR */, 400, {
3188
+ ...options,
3189
+ details: { ...options?.details, validationErrors }
3190
+ });
3191
+ this.name = "OCXPValidationError";
3192
+ this.validationErrors = validationErrors;
3193
+ }
3194
+ };
3195
+ var OCXPAuthError = class extends OCXPError {
3196
+ constructor(message, options) {
3197
+ super(message, "AUTH_ERROR" /* AUTH_ERROR */, 401, options);
3198
+ this.name = "OCXPAuthError";
3199
+ }
3200
+ };
3201
+ var OCXPNotFoundError = class extends OCXPError {
3202
+ /** The resource path that was not found */
3203
+ path;
3204
+ constructor(message, path, options) {
3205
+ super(message, "NOT_FOUND" /* NOT_FOUND */, 404, {
3206
+ ...options,
3207
+ details: { ...options?.details, path }
3208
+ });
3209
+ this.name = "OCXPNotFoundError";
3210
+ this.path = path;
3211
+ }
3212
+ };
3213
+ var OCXPRateLimitError = class extends OCXPError {
3214
+ /** Seconds until rate limit resets */
3215
+ retryAfter;
3216
+ constructor(message = "Rate limit exceeded", retryAfter, options) {
3217
+ super(message, "RATE_LIMITED" /* RATE_LIMITED */, 429, {
3218
+ ...options,
3219
+ details: { ...options?.details, retryAfter }
3220
+ });
3221
+ this.name = "OCXPRateLimitError";
3222
+ this.retryAfter = retryAfter;
3223
+ }
3224
+ };
3225
+ var OCXPConflictError = class extends OCXPError {
3226
+ /** Expected etag value */
3227
+ expectedEtag;
3228
+ /** Actual etag value */
3229
+ actualEtag;
3230
+ constructor(message, options) {
3231
+ super(message, "CONFLICT" /* CONFLICT */, 409, {
3232
+ details: {
3233
+ ...options?.details,
3234
+ expectedEtag: options?.expectedEtag,
3235
+ actualEtag: options?.actualEtag
3236
+ },
3237
+ requestId: options?.requestId,
3238
+ cause: options?.cause
3239
+ });
3240
+ this.name = "OCXPConflictError";
3241
+ this.expectedEtag = options?.expectedEtag;
3242
+ this.actualEtag = options?.actualEtag;
3243
+ }
3244
+ };
3245
+ var OCXPTimeoutError = class extends OCXPError {
3246
+ /** Timeout duration in milliseconds */
3247
+ timeoutMs;
3248
+ constructor(message = "Operation timed out", timeoutMs, options) {
3249
+ super(message, "TIMEOUT" /* TIMEOUT */, 408, {
3250
+ ...options,
3251
+ details: { ...options?.details, timeoutMs }
3252
+ });
3253
+ this.name = "OCXPTimeoutError";
3254
+ this.timeoutMs = timeoutMs;
3255
+ }
3256
+ };
3257
+ function isOCXPError(error) {
3258
+ return error instanceof OCXPError;
3259
+ }
3260
+ function isOCXPNetworkError(error) {
3261
+ return error instanceof OCXPNetworkError;
3262
+ }
3263
+ function isOCXPValidationError(error) {
3264
+ return error instanceof OCXPValidationError;
3265
+ }
3266
+ function isOCXPAuthError(error) {
3267
+ return error instanceof OCXPAuthError;
3268
+ }
3269
+ function isOCXPNotFoundError(error) {
3270
+ return error instanceof OCXPNotFoundError;
3271
+ }
3272
+ function isOCXPRateLimitError(error) {
3273
+ return error instanceof OCXPRateLimitError;
3274
+ }
3275
+ function isOCXPConflictError(error) {
3276
+ return error instanceof OCXPConflictError;
3277
+ }
3278
+ function isOCXPTimeoutError(error) {
3279
+ return error instanceof OCXPTimeoutError;
3280
+ }
3281
+ function mapHttpError(statusCode, message, options) {
3282
+ const baseOptions = {
3283
+ details: options?.details,
3284
+ requestId: options?.requestId
3285
+ };
3286
+ switch (statusCode) {
3287
+ case 400:
3288
+ return new OCXPValidationError(message, void 0, baseOptions);
3289
+ case 401:
3290
+ case 403:
3291
+ return new OCXPAuthError(message, baseOptions);
3292
+ case 404:
3293
+ return new OCXPNotFoundError(message, options?.path, baseOptions);
3294
+ case 408:
3295
+ return new OCXPTimeoutError(message, void 0, baseOptions);
3296
+ case 409:
3297
+ return new OCXPConflictError(message, baseOptions);
3298
+ case 429:
3299
+ return new OCXPRateLimitError(message, options?.retryAfter, baseOptions);
3300
+ default:
3301
+ if (statusCode >= 500) {
3302
+ return new OCXPError(message, "SERVER_ERROR" /* SERVER_ERROR */, statusCode, baseOptions);
3303
+ }
3304
+ return new OCXPError(message, "UNKNOWN" /* UNKNOWN */, statusCode, baseOptions);
3305
+ }
3306
+ }
3307
+ var MetaSchema = z.object({
3308
+ requestId: z.string(),
3309
+ timestamp: z.string(),
3310
+ durationMs: z.number(),
3311
+ operation: z.string()
3312
+ });
3313
+ var ErrorResponseSchema = z.object({
3314
+ code: z.string(),
3315
+ message: z.string(),
3316
+ details: z.record(z.string(), z.unknown()).optional()
3317
+ });
3318
+ var OCXPResponseSchema = z.object({
3319
+ success: z.boolean(),
3320
+ data: z.unknown().optional(),
3321
+ error: ErrorResponseSchema.nullable().optional(),
3322
+ notifications: z.array(z.unknown()).optional(),
3323
+ meta: MetaSchema.optional()
3324
+ });
3325
+ var PaginationSchema = z.object({
3326
+ cursor: z.string().nullable().optional(),
3327
+ hasMore: z.boolean(),
3328
+ total: z.number()
3329
+ });
3330
+ var ContentTypeSchema = z.enum([
3331
+ "mission",
3332
+ "project",
3333
+ "context",
3334
+ "sop",
3335
+ "repo",
3336
+ "artifact",
3337
+ "kb",
3338
+ "docs"
3339
+ ]);
3340
+ function createResponseSchema(dataSchema) {
3341
+ return z.object({
3342
+ success: z.boolean(),
3343
+ data: dataSchema.optional(),
3344
+ error: ErrorResponseSchema.nullable().optional(),
3345
+ notifications: z.array(z.unknown()).optional(),
3346
+ meta: MetaSchema.optional()
3347
+ });
3348
+ }
3349
+ var ListEntrySchema = z.object({
3350
+ name: z.string(),
3351
+ type: z.enum(["file", "directory"]),
3352
+ path: z.string(),
3353
+ size: z.number().optional(),
3354
+ mtime: z.string().optional()
3355
+ });
3356
+ var ListDataSchema = z.object({
3357
+ entries: z.array(ListEntrySchema),
3358
+ cursor: z.string().nullable().optional(),
3359
+ hasMore: z.boolean().optional().default(false),
3360
+ total: z.number().optional().default(0)
3361
+ });
3362
+ var ListResponseSchema = createResponseSchema(ListDataSchema);
3363
+ var ReadDataSchema = z.object({
3364
+ content: z.string(),
3365
+ size: z.number().optional(),
3366
+ mtime: z.string().optional(),
3367
+ encoding: z.string().optional(),
3368
+ metadata: z.record(z.string(), z.unknown()).optional(),
3369
+ etag: z.string().optional()
3370
+ });
3371
+ var ReadResponseSchema = createResponseSchema(ReadDataSchema);
3372
+ var WriteDataSchema = z.object({
3373
+ path: z.string(),
3374
+ etag: z.string().optional(),
3375
+ size: z.number().optional()
3376
+ });
3377
+ var WriteResponseSchema = createResponseSchema(WriteDataSchema);
3378
+ var DeleteDataSchema = z.object({
3379
+ path: z.string(),
3380
+ deleted: z.boolean().optional().default(true)
3381
+ });
3382
+ var DeleteResponseSchema = createResponseSchema(DeleteDataSchema);
3383
+ var QueryFilterSchema = z.object({
3384
+ field: z.string(),
3385
+ operator: z.enum(["eq", "ne", "gt", "lt", "gte", "lte", "contains", "startsWith"]),
3386
+ value: z.unknown()
3387
+ });
3388
+ var QueryDataSchema = z.object({
3389
+ items: z.array(z.record(z.string(), z.unknown())),
3390
+ cursor: z.string().nullable().optional(),
3391
+ hasMore: z.boolean().optional().default(false),
3392
+ total: z.number().optional().default(0)
3393
+ });
3394
+ var QueryResponseSchema = createResponseSchema(QueryDataSchema);
3395
+ var SearchDataSchema = z.object({
3396
+ results: z.array(
3397
+ z.object({
3398
+ path: z.string(),
3399
+ score: z.number().optional(),
3400
+ highlights: z.array(z.string()).optional(),
3401
+ content: z.string().optional()
3402
+ })
3403
+ ),
3404
+ total: z.number().optional().default(0)
3405
+ });
3406
+ var SearchResponseSchema = createResponseSchema(SearchDataSchema);
3407
+ var TreeNodeSchema = z.lazy(
3408
+ () => z.object({
3409
+ name: z.string(),
3410
+ path: z.string(),
3411
+ type: z.enum(["file", "directory"]),
3412
+ size: z.number().optional(),
3413
+ children: z.array(TreeNodeSchema).optional()
3414
+ })
3415
+ );
3416
+ var TreeDataSchema = z.object({
3417
+ root: TreeNodeSchema,
3418
+ depth: z.number().optional()
3419
+ });
3420
+ var TreeResponseSchema = createResponseSchema(TreeDataSchema);
3421
+ var StatsDataSchema = z.object({
3422
+ totalFiles: z.number(),
3423
+ totalSize: z.number(),
3424
+ lastModified: z.string().optional(),
3425
+ fileTypes: z.record(z.string(), z.number()).optional()
3426
+ });
3427
+ var StatsResponseSchema = createResponseSchema(StatsDataSchema);
3428
+ var ContentTypeInfoSchema = z.object({
3429
+ name: z.string(),
3430
+ description: z.string().optional(),
3431
+ prefix: z.string().nullable().optional(),
3432
+ isVirtual: z.boolean().optional(),
3433
+ isGlobal: z.boolean().optional(),
3434
+ count: z.number().nullable().optional(),
3435
+ endpoints: z.record(z.string(), z.string()).optional()
3436
+ });
3437
+ var ContentTypesDataSchema = z.object({
3438
+ types: z.array(ContentTypeInfoSchema)
3439
+ });
3440
+ var ContentTypesResponseSchema = createResponseSchema(ContentTypesDataSchema);
3441
+ var PresignedUrlDataSchema = z.object({
3442
+ url: z.string(),
3443
+ expiresAt: z.string().optional(),
3444
+ method: z.enum(["GET", "PUT"]).optional()
3445
+ });
3446
+ var PresignedUrlResponseSchema = createResponseSchema(PresignedUrlDataSchema);
3447
+ var SessionMessageSchema = z.object({
3448
+ id: z.string(),
3449
+ role: z.enum(["user", "assistant", "system"]),
3450
+ content: z.string(),
3451
+ timestamp: z.string(),
3452
+ metadata: z.record(z.string(), z.unknown()).optional()
3453
+ });
3454
+ var SessionSchema = z.object({
3455
+ id: z.string(),
3456
+ missionId: z.string().optional(),
3457
+ title: z.string().optional(),
3458
+ createdAt: z.string(),
3459
+ updatedAt: z.string().optional(),
3460
+ metadata: z.record(z.string(), z.unknown()).optional(),
3461
+ messageCount: z.number().optional()
3462
+ });
3463
+ var ListSessionsDataSchema = z.object({
3464
+ sessions: z.array(SessionSchema),
3465
+ total: z.number().optional()
3466
+ });
3467
+ var ListSessionsResponseSchema = createResponseSchema(ListSessionsDataSchema);
3468
+ var CreateSessionDataSchema = z.object({
3469
+ sessionId: z.string(),
3470
+ missionId: z.string().optional()
3471
+ });
3472
+ var CreateSessionResponseSchema = createResponseSchema(CreateSessionDataSchema);
3473
+ var GetSessionMessagesDataSchema = z.object({
3474
+ messages: z.array(SessionMessageSchema),
3475
+ sessionId: z.string()
3476
+ });
3477
+ var GetSessionMessagesResponseSchema = createResponseSchema(GetSessionMessagesDataSchema);
3478
+ var UpdateSessionMetadataDataSchema = z.object({
3479
+ sessionId: z.string(),
3480
+ metadata: z.record(z.string(), z.unknown())
3481
+ });
3482
+ var UpdateSessionMetadataResponseSchema = createResponseSchema(
3483
+ UpdateSessionMetadataDataSchema
3484
+ );
3485
+ var ForkSessionDataSchema = z.object({
3486
+ sessionId: z.string(),
3487
+ forkedFromId: z.string()
3488
+ });
3489
+ var ForkSessionResponseSchema = createResponseSchema(ForkSessionDataSchema);
3490
+ var ProjectRepoSchema = z.object({
3491
+ repoId: z.string(),
3492
+ isDefault: z.boolean().optional(),
3493
+ addedAt: z.string().optional()
3494
+ });
3495
+ var ProjectMissionSchema = z.object({
3496
+ missionId: z.string(),
3497
+ addedAt: z.string().optional()
3498
+ });
3499
+ var ProjectSchema = z.object({
3500
+ id: z.string(),
3501
+ name: z.string(),
3502
+ description: z.string().optional(),
3503
+ createdAt: z.string(),
3504
+ updatedAt: z.string().optional(),
3505
+ repos: z.array(ProjectRepoSchema).optional(),
3506
+ missions: z.array(ProjectMissionSchema).optional(),
3507
+ defaultRepoId: z.string().optional(),
3508
+ metadata: z.record(z.string(), z.unknown()).optional()
3509
+ });
3510
+ var ListProjectsDataSchema = z.object({
3511
+ projects: z.array(ProjectSchema),
3512
+ total: z.number().optional()
3513
+ });
3514
+ var ListProjectsResponseSchema = createResponseSchema(ListProjectsDataSchema);
3515
+ var CreateProjectDataSchema = z.object({
3516
+ projectId: z.string(),
3517
+ project: ProjectSchema.optional()
3518
+ });
3519
+ var CreateProjectResponseSchema = createResponseSchema(CreateProjectDataSchema);
3520
+ var GetProjectDataSchema = ProjectSchema;
3521
+ var GetProjectResponseSchema = createResponseSchema(GetProjectDataSchema);
3522
+ var UpdateProjectDataSchema = z.object({
3523
+ projectId: z.string(),
3524
+ project: ProjectSchema.optional()
3525
+ });
3526
+ var UpdateProjectResponseSchema = createResponseSchema(UpdateProjectDataSchema);
3527
+ var DeleteProjectDataSchema = z.object({
3528
+ projectId: z.string(),
3529
+ deleted: z.boolean()
3530
+ });
3531
+ var DeleteProjectResponseSchema = createResponseSchema(DeleteProjectDataSchema);
3532
+ var AddProjectRepoDataSchema = z.object({
3533
+ projectId: z.string(),
3534
+ repoId: z.string()
3535
+ });
3536
+ var AddProjectRepoResponseSchema = createResponseSchema(AddProjectRepoDataSchema);
3537
+ var ContextReposDataSchema = z.object({
3538
+ repos: z.array(
3539
+ z.object({
3540
+ repoId: z.string(),
3541
+ name: z.string().optional(),
3542
+ isDefault: z.boolean().optional()
3543
+ })
3544
+ )
3545
+ });
3546
+ var ContextReposResponseSchema = createResponseSchema(ContextReposDataSchema);
3547
+ var RepoStatusEnum = z.enum([
3548
+ "queued",
3549
+ "processing",
3550
+ "uploading",
3551
+ "vectorizing",
3552
+ "complete",
3553
+ "failed"
3554
+ ]);
3555
+ var RepoDownloadRequestSchema = z.object({
3556
+ github_url: z.string(),
3557
+ repo_id: z.string(),
3558
+ branch: z.string().optional().default("main"),
3559
+ path: z.string().nullable().optional(),
3560
+ mode: z.enum(["full", "docs_only"]).optional().default("full"),
3561
+ include_extensions: z.array(z.string()).optional(),
3562
+ exclude_patterns: z.array(z.string()).optional(),
3563
+ max_file_size_kb: z.number().min(1).max(5e3).optional().default(500),
3564
+ visibility: z.enum(["private", "public"]).optional().default("private"),
3565
+ trigger_vectorization: z.boolean().optional().default(true),
3566
+ generate_metadata: z.boolean().optional().default(true),
3567
+ is_private: z.boolean().optional().default(false)
3568
+ });
3569
+ var RepoDownloadDataSchema = z.object({
3570
+ repo_id: z.string(),
3571
+ job_id: z.string(),
3572
+ s3_path: z.string().optional(),
3573
+ status: RepoStatusEnum,
3574
+ files_processed: z.number().optional(),
3575
+ metadata_files_created: z.number().optional(),
3576
+ ingestion_job_id: z.string().nullable().optional()
3577
+ });
3578
+ var RepoDownloadResponseSchema = createResponseSchema(RepoDownloadDataSchema);
3579
+ var RepoStatusDataSchema = z.object({
3580
+ job_id: z.string(),
3581
+ status: RepoStatusEnum,
3582
+ progress: z.number().min(0).max(100).optional(),
3583
+ files_processed: z.number().optional(),
3584
+ total_files: z.number().optional(),
3585
+ error: z.string().nullable().optional(),
3586
+ started_at: z.string().nullable().optional(),
3587
+ completed_at: z.string().nullable().optional()
3588
+ });
3589
+ var RepoStatusResponseSchema = createResponseSchema(RepoStatusDataSchema);
3590
+ var RepoListItemSchema = z.object({
3591
+ repo_id: z.string(),
3592
+ github_url: z.string().optional(),
3593
+ branch: z.string().optional(),
3594
+ visibility: z.enum(["private", "public"]).optional(),
3595
+ mode: z.enum(["full", "docs_only"]).optional(),
3596
+ files_count: z.number().optional(),
3597
+ last_synced: z.string().optional(),
3598
+ s3_path: z.string().optional()
3599
+ });
3600
+ var RepoListDataSchema = z.object({
3601
+ repos: z.array(RepoListItemSchema),
3602
+ total: z.number().optional()
3603
+ });
3604
+ var RepoListResponseSchema = createResponseSchema(RepoListDataSchema);
3605
+ var RepoExistsDataSchema = z.object({
3606
+ repo_id: z.string(),
3607
+ exists: z.boolean(),
3608
+ indexed_at: z.string().nullable().optional(),
3609
+ files_count: z.number().optional()
3610
+ });
3611
+ var RepoExistsResponseSchema = createResponseSchema(RepoExistsDataSchema);
3612
+ var RepoDeleteDataSchema = z.object({
3613
+ repo_id: z.string(),
3614
+ success: z.boolean(),
3615
+ s3_files_deleted: z.number().optional(),
3616
+ projects_updated: z.number().optional(),
3617
+ error: z.string().optional()
3618
+ });
3619
+ var RepoDeleteResponseSchema = createResponseSchema(RepoDeleteDataSchema);
3620
+ var AuthTokenDataSchema = z.object({
3621
+ accessToken: z.string(),
3622
+ tokenType: z.string().optional().default("Bearer"),
3623
+ expiresIn: z.number().optional(),
3624
+ expiresAt: z.string().optional(),
3625
+ refreshToken: z.string().optional(),
3626
+ scope: z.string().optional()
3627
+ });
3628
+ var AuthTokenResponseSchema = createResponseSchema(AuthTokenDataSchema);
3629
+ var AuthUserInfoSchema = z.object({
3630
+ userId: z.string(),
3631
+ email: z.string().optional(),
3632
+ name: z.string().optional(),
3633
+ roles: z.array(z.string()).optional(),
3634
+ permissions: z.array(z.string()).optional(),
3635
+ metadata: z.record(z.string(), z.unknown()).optional()
3636
+ });
3637
+ var AuthUserInfoResponseSchema = createResponseSchema(AuthUserInfoSchema);
3638
+ var AuthValidateDataSchema = z.object({
3639
+ valid: z.boolean(),
3640
+ userId: z.string().optional(),
3641
+ expiresAt: z.string().optional()
3642
+ });
3643
+ var AuthValidateResponseSchema = createResponseSchema(AuthValidateDataSchema);
3644
+ var SearchResultItemSchema = z.object({
3645
+ id: z.string(),
3646
+ path: z.string().optional(),
3647
+ content: z.string().optional(),
3648
+ score: z.number().optional(),
3649
+ highlights: z.array(z.string()).optional(),
3650
+ metadata: z.record(z.string(), z.unknown()).optional(),
3651
+ source: z.string().optional(),
3652
+ type: z.string().optional()
3653
+ });
3654
+ var VectorSearchDataSchema = z.object({
3655
+ results: z.array(SearchResultItemSchema),
3656
+ total: z.number().optional(),
3657
+ query: z.string().optional(),
3658
+ processingTimeMs: z.number().optional()
3659
+ });
3660
+ var VectorSearchResponseSchema = createResponseSchema(VectorSearchDataSchema);
3661
+ var KBDocumentSchema = z.object({
3662
+ id: z.string(),
3663
+ title: z.string().optional(),
3664
+ content: z.string(),
3665
+ path: z.string().optional(),
3666
+ source: z.string().optional(),
3667
+ createdAt: z.string().optional(),
3668
+ updatedAt: z.string().optional(),
3669
+ metadata: z.record(z.string(), z.unknown()).optional(),
3670
+ vectorId: z.string().optional()
3671
+ });
3672
+ var KBListDataSchema = z.object({
3673
+ documents: z.array(KBDocumentSchema),
3674
+ total: z.number().optional(),
3675
+ cursor: z.string().nullable().optional(),
3676
+ hasMore: z.boolean().optional()
3677
+ });
3678
+ var KBListResponseSchema = createResponseSchema(KBListDataSchema);
3679
+ var KBIngestDataSchema = z.object({
3680
+ documentId: z.string(),
3681
+ vectorId: z.string().optional(),
3682
+ chunksCreated: z.number().optional(),
3683
+ status: z.enum(["pending", "processing", "complete", "failed"]).optional()
3684
+ });
3685
+ var KBIngestResponseSchema = createResponseSchema(KBIngestDataSchema);
3686
+ var DiscoveryEndpointSchema = z.object({
3687
+ name: z.string(),
3688
+ path: z.string(),
3689
+ methods: z.array(z.string()),
3690
+ description: z.string().optional(),
3691
+ parameters: z.array(z.record(z.string(), z.unknown())).optional()
3692
+ });
3693
+ var DiscoveryDataSchema = z.object({
3694
+ version: z.string().optional(),
3695
+ endpoints: z.array(DiscoveryEndpointSchema),
3696
+ contentTypes: z.array(z.string()).optional(),
3697
+ capabilities: z.array(z.string()).optional()
3698
+ });
3699
+ var DiscoveryResponseSchema = createResponseSchema(DiscoveryDataSchema);
3700
+ var IngestionJobSchema = z.object({
3701
+ jobId: z.string(),
3702
+ status: z.enum(["queued", "processing", "complete", "failed"]),
3703
+ progress: z.number().min(0).max(100).optional(),
3704
+ documentsProcessed: z.number().optional(),
3705
+ totalDocuments: z.number().optional(),
3706
+ error: z.string().nullable().optional(),
3707
+ startedAt: z.string().nullable().optional(),
3708
+ completedAt: z.string().nullable().optional()
3709
+ });
3710
+ var IngestionJobResponseSchema = createResponseSchema(IngestionJobSchema);
3711
+ var WSMessageTypeSchema = z.enum([
3712
+ "chat",
3713
+ "chat_response",
3714
+ "stream_start",
3715
+ "stream_chunk",
3716
+ "stream_end",
3717
+ "error",
3718
+ "ping",
3719
+ "pong",
3720
+ "connected",
3721
+ "disconnected",
3722
+ "session_start",
3723
+ "session_end",
3724
+ "typing",
3725
+ "status"
3726
+ ]);
3727
+ var WSBaseMessageSchema = z.object({
3728
+ type: WSMessageTypeSchema,
3729
+ id: z.string().optional(),
3730
+ timestamp: z.string().optional(),
3731
+ sessionId: z.string().optional()
3732
+ });
3733
+ var WSChatMessageSchema = WSBaseMessageSchema.extend({
3734
+ type: z.literal("chat"),
3735
+ content: z.string(),
3736
+ missionId: z.string().optional(),
3737
+ projectId: z.string().optional(),
3738
+ metadata: z.record(z.string(), z.unknown()).optional()
3739
+ });
3740
+ var WSChatResponseSchema = WSBaseMessageSchema.extend({
3741
+ type: z.literal("chat_response"),
3742
+ content: z.string(),
3743
+ role: z.enum(["assistant", "system"]).optional(),
3744
+ metadata: z.record(z.string(), z.unknown()).optional(),
3745
+ usage: z.object({
3746
+ promptTokens: z.number().optional(),
3747
+ completionTokens: z.number().optional(),
3748
+ totalTokens: z.number().optional()
3749
+ }).optional()
3750
+ });
3751
+ var WSStreamStartSchema = WSBaseMessageSchema.extend({
3752
+ type: z.literal("stream_start"),
3753
+ streamId: z.string()
3754
+ });
3755
+ var WSStreamChunkSchema = WSBaseMessageSchema.extend({
3756
+ type: z.literal("stream_chunk"),
3757
+ streamId: z.string(),
3758
+ content: z.string(),
3759
+ index: z.number().optional()
3760
+ });
3761
+ var WSStreamEndSchema = WSBaseMessageSchema.extend({
3762
+ type: z.literal("stream_end"),
3763
+ streamId: z.string(),
3764
+ usage: z.object({
3765
+ promptTokens: z.number().optional(),
3766
+ completionTokens: z.number().optional(),
3767
+ totalTokens: z.number().optional()
3768
+ }).optional()
3769
+ });
3770
+ var WSErrorMessageSchema = WSBaseMessageSchema.extend({
3771
+ type: z.literal("error"),
3772
+ code: z.string(),
3773
+ message: z.string(),
3774
+ details: z.record(z.string(), z.unknown()).optional()
3775
+ });
3776
+ var WSPingPongSchema = WSBaseMessageSchema.extend({
3777
+ type: z.enum(["ping", "pong"])
3778
+ });
3779
+ var WSConnectedSchema = WSBaseMessageSchema.extend({
3780
+ type: z.literal("connected"),
3781
+ connectionId: z.string().optional(),
3782
+ serverVersion: z.string().optional()
3783
+ });
3784
+ var WSStatusSchema = WSBaseMessageSchema.extend({
3785
+ type: z.literal("status"),
3786
+ status: z.enum(["ready", "busy", "processing", "idle"]),
3787
+ message: z.string().optional()
3788
+ });
3789
+ var WSMessageSchema = z.discriminatedUnion("type", [
3790
+ WSChatMessageSchema,
3791
+ WSChatResponseSchema,
3792
+ WSStreamStartSchema,
3793
+ WSStreamChunkSchema,
3794
+ WSStreamEndSchema,
3795
+ WSErrorMessageSchema,
3796
+ WSPingPongSchema.extend({ type: z.literal("ping") }),
3797
+ WSPingPongSchema.extend({ type: z.literal("pong") }),
3798
+ WSConnectedSchema,
3799
+ WSStatusSchema
3800
+ ]);
3801
+ function parseWSMessage(data) {
3802
+ const parsed = JSON.parse(data);
3803
+ return WSMessageSchema.parse(parsed);
3804
+ }
3805
+ function safeParseWSMessage(data) {
3806
+ try {
3807
+ const parsed = JSON.parse(data);
3808
+ const result = WSMessageSchema.safeParse(parsed);
3809
+ if (result.success) {
3810
+ return { success: true, data: result.data };
3811
+ }
3812
+ return { success: false, error: result.error };
3813
+ } catch {
3814
+ return {
3815
+ success: false,
3816
+ error: new z.ZodError([
3817
+ {
3818
+ code: "custom",
3819
+ message: "Invalid JSON",
3820
+ path: []
3821
+ }
3822
+ ])
3823
+ };
3824
+ }
3825
+ }
3826
+ var GithubFileInfoSchema = z.object({
3827
+ name: z.string(),
3828
+ path: z.string(),
3829
+ sha: z.string(),
3830
+ size: z.number(),
3831
+ type: z.enum(["file", "dir", "symlink", "submodule"]),
3832
+ url: z.string().optional(),
3833
+ html_url: z.string().optional(),
3834
+ git_url: z.string().optional(),
3835
+ download_url: z.string().nullable().optional(),
3836
+ content: z.string().optional(),
3837
+ encoding: z.string().optional()
3838
+ });
3839
+ var GithubRepoInfoSchema = z.object({
3840
+ id: z.number(),
3841
+ name: z.string(),
3842
+ full_name: z.string(),
3843
+ private: z.boolean(),
3844
+ owner: z.object({
3845
+ login: z.string(),
3846
+ id: z.number(),
3847
+ avatar_url: z.string().optional(),
3848
+ type: z.string().optional()
3849
+ }),
3850
+ html_url: z.string(),
3851
+ description: z.string().nullable().optional(),
3852
+ fork: z.boolean().optional(),
3853
+ created_at: z.string().optional(),
3854
+ updated_at: z.string().optional(),
3855
+ pushed_at: z.string().optional(),
3856
+ size: z.number().optional(),
3857
+ stargazers_count: z.number().optional(),
3858
+ watchers_count: z.number().optional(),
3859
+ language: z.string().nullable().optional(),
3860
+ default_branch: z.string().optional(),
3861
+ visibility: z.string().optional()
3862
+ });
3863
+ var GithubBranchInfoSchema = z.object({
3864
+ name: z.string(),
3865
+ commit: z.object({
3866
+ sha: z.string(),
3867
+ url: z.string().optional()
3868
+ }),
3869
+ protected: z.boolean().optional()
3870
+ });
3871
+ var GithubCommitInfoSchema = z.object({
3872
+ sha: z.string(),
3873
+ message: z.string().optional(),
3874
+ author: z.object({
3875
+ name: z.string().optional(),
3876
+ email: z.string().optional(),
3877
+ date: z.string().optional()
3878
+ }).optional(),
3879
+ committer: z.object({
3880
+ name: z.string().optional(),
3881
+ email: z.string().optional(),
3882
+ date: z.string().optional()
3883
+ }).optional(),
3884
+ url: z.string().optional(),
3885
+ html_url: z.string().optional()
3886
+ });
3887
+ var GithubFileDataSchema = z.object({
3888
+ file: GithubFileInfoSchema,
3889
+ content: z.string().optional(),
3890
+ encoding: z.string().optional()
3891
+ });
3892
+ var GithubFileResponseSchema = createResponseSchema(GithubFileDataSchema);
3893
+ var GithubDirectoryDataSchema = z.object({
3894
+ entries: z.array(GithubFileInfoSchema),
3895
+ path: z.string()
3896
+ });
3897
+ var GithubDirectoryResponseSchema = createResponseSchema(GithubDirectoryDataSchema);
3898
+ var GithubRepoDataSchema = z.object({
3899
+ repository: GithubRepoInfoSchema
3900
+ });
3901
+ var GithubRepoResponseSchema = createResponseSchema(GithubRepoDataSchema);
3902
+ var GithubBranchesDataSchema = z.object({
3903
+ branches: z.array(GithubBranchInfoSchema)
3904
+ });
3905
+ var GithubBranchesResponseSchema = createResponseSchema(GithubBranchesDataSchema);
3906
+ var GithubCommitsDataSchema = z.object({
3907
+ commits: z.array(GithubCommitInfoSchema)
3908
+ });
3909
+ var GithubCommitsResponseSchema = createResponseSchema(GithubCommitsDataSchema);
3910
+
3911
+ export { AddProjectRepoDataSchema, AddProjectRepoResponseSchema, AuthTokenDataSchema, AuthTokenResponseSchema, AuthUserInfoResponseSchema, AuthUserInfoSchema, AuthValidateDataSchema, AuthValidateResponseSchema, ContentTypeInfoSchema, ContentTypeSchema, ContentTypesDataSchema, ContentTypesResponseSchema, ContextReposDataSchema, ContextReposResponseSchema, CreateProjectDataSchema, CreateProjectResponseSchema, CreateSessionDataSchema, CreateSessionResponseSchema, DeleteDataSchema, DeleteProjectDataSchema, DeleteProjectResponseSchema, DeleteResponseSchema, DiscoveryDataSchema, DiscoveryEndpointSchema, DiscoveryResponseSchema, ErrorResponseSchema, ForkSessionDataSchema, ForkSessionResponseSchema, GetProjectDataSchema, GetProjectResponseSchema, GetSessionMessagesDataSchema, GetSessionMessagesResponseSchema, GithubBranchInfoSchema, GithubBranchesDataSchema, GithubBranchesResponseSchema, GithubCommitInfoSchema, GithubCommitsDataSchema, GithubCommitsResponseSchema, GithubDirectoryDataSchema, GithubDirectoryResponseSchema, GithubFileDataSchema, GithubFileInfoSchema, GithubFileResponseSchema, GithubRepoDataSchema, GithubRepoInfoSchema, GithubRepoResponseSchema, IngestionJobResponseSchema, IngestionJobSchema, KBDocumentSchema, KBIngestDataSchema, KBIngestResponseSchema, KBListDataSchema, KBListResponseSchema, KBNamespace, ListDataSchema, ListEntrySchema, ListProjectsDataSchema, ListProjectsResponseSchema, ListResponseSchema, ListSessionsDataSchema, ListSessionsResponseSchema, MetaSchema, MissionNamespace, OCXPAuthError, OCXPClient, OCXPConflictError, OCXPError, OCXPErrorCode, OCXPNetworkError, OCXPNotFoundError, OCXPPathService, OCXPRateLimitError, OCXPResponseSchema, OCXPTimeoutError, OCXPValidationError, PaginationSchema, PresignedUrlDataSchema, PresignedUrlResponseSchema, ProjectMissionSchema, ProjectNamespace, ProjectRepoSchema, ProjectSchema, QueryDataSchema, QueryFilterSchema, QueryResponseSchema, ReadDataSchema, ReadResponseSchema, RepoDeleteDataSchema, RepoDeleteResponseSchema, RepoDownloadDataSchema, RepoDownloadRequestSchema, RepoDownloadResponseSchema, RepoExistsDataSchema, RepoExistsResponseSchema, RepoListDataSchema, RepoListItemSchema, RepoListResponseSchema, RepoStatusDataSchema, RepoStatusEnum, RepoStatusResponseSchema, SearchDataSchema, SearchResponseSchema, SearchResultItemSchema, SessionMessageSchema, SessionNamespace, SessionSchema, StatsDataSchema, StatsResponseSchema, TreeDataSchema, TreeNodeSchema, TreeResponseSchema, UpdateProjectDataSchema, UpdateProjectResponseSchema, UpdateSessionMetadataDataSchema, UpdateSessionMetadataResponseSchema, VALID_CONTENT_TYPES, VectorSearchDataSchema, VectorSearchResponseSchema, WSBaseMessageSchema, WSChatMessageSchema, WSChatResponseSchema, WSConnectedSchema, WSErrorMessageSchema, WSMessageSchema, WSMessageTypeSchema, WSPingPongSchema, WSStatusSchema, WSStreamChunkSchema, WSStreamEndSchema, WSStreamStartSchema, WebSocketService, WriteDataSchema, WriteResponseSchema, acknowledgeMemo, addDatabase, addLinkedRepo, addMission, archiveSession, buildPath, bulkDeleteContent, bulkReadContent, bulkWriteContent, createClient, createConfig, createDatabase, createMemo, createOCXPClient, createPathService, createProject, createResponseSchema, createWebSocketService, deleteContent, deleteDatabase, deleteMemo, deleteProject, deleteRepo, downloadRepository, forkSession, getAuthConfig, getCanonicalType, getContentStats, getContentTree, getContentTypes, getContextRepos, getCurrentUser, getDatabase, getMemo, getMemoForSource, getMissionContext, getProject, getProjectDatabases, getRepoDownloadStatus, getSample, getSchema, getSessionMessages, githubCheckAccess, githubGetContents, githubListBranches, ignoreMemo, isOCXPAuthError, isOCXPConflictError, isOCXPError, isOCXPNetworkError, isOCXPNotFoundError, isOCXPRateLimitError, isOCXPTimeoutError, isOCXPValidationError, isValidContentType, listContent, listContextDatabases, listDatabases, listDownloadedRepos, listMemos, listProjects, listSessions, listTables, listWorkspaces, lockContent, login, loginForAccessToken, mapHttpError, moveContent, normalizePath, parsePath, parseWSMessage, queryContent, queryKnowledgeBase, ragKnowledgeBase, readContent, refreshTokens, regenerateMission, removeDatabase, removeLinkedRepo, removeMission, resolveMemo, safeParseWSMessage, searchContent, setDefaultDatabase, setDefaultRepo, testDatabaseConnection, toolCreateMission, toolUpdateMission, unlockContent, updateDatabase, updateProject, updateSessionMetadata, writeContent };
3912
+ //# sourceMappingURL=index.js.map
3913
+ //# sourceMappingURL=index.js.map