@vectorize-io/hindsight-client 0.4.18 → 0.4.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/{generated/types.gen.d.ts → index.d.mts} +1426 -362
  2. package/dist/index.d.ts +5384 -0
  3. package/dist/index.js +1597 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.mjs +1572 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/generated/client/client.gen.ts +3 -1
  8. package/generated/sdk.gen.ts +17 -0
  9. package/generated/types.gen.ts +63 -1
  10. package/package.json +15 -5
  11. package/src/index.ts +2 -0
  12. package/dist/generated/client/client.gen.d.ts +0 -3
  13. package/dist/generated/client/client.gen.d.ts.map +0 -1
  14. package/dist/generated/client/client.gen.js +0 -233
  15. package/dist/generated/client/client.gen.js.map +0 -1
  16. package/dist/generated/client/index.d.ts +0 -9
  17. package/dist/generated/client/index.d.ts.map +0 -1
  18. package/dist/generated/client/index.js +0 -18
  19. package/dist/generated/client/index.js.map +0 -1
  20. package/dist/generated/client/types.gen.d.ts +0 -118
  21. package/dist/generated/client/types.gen.d.ts.map +0 -1
  22. package/dist/generated/client/types.gen.js +0 -4
  23. package/dist/generated/client/types.gen.js.map +0 -1
  24. package/dist/generated/client/utils.gen.d.ts +0 -34
  25. package/dist/generated/client/utils.gen.d.ts.map +0 -1
  26. package/dist/generated/client/utils.gen.js +0 -245
  27. package/dist/generated/client/utils.gen.js.map +0 -1
  28. package/dist/generated/client.gen.d.ts +0 -13
  29. package/dist/generated/client.gen.d.ts.map +0 -1
  30. package/dist/generated/client.gen.js +0 -7
  31. package/dist/generated/client.gen.js.map +0 -1
  32. package/dist/generated/core/auth.gen.d.ts +0 -19
  33. package/dist/generated/core/auth.gen.d.ts.map +0 -1
  34. package/dist/generated/core/auth.gen.js +0 -19
  35. package/dist/generated/core/auth.gen.js.map +0 -1
  36. package/dist/generated/core/bodySerializer.gen.d.ts +0 -26
  37. package/dist/generated/core/bodySerializer.gen.d.ts.map +0 -1
  38. package/dist/generated/core/bodySerializer.gen.js +0 -61
  39. package/dist/generated/core/bodySerializer.gen.js.map +0 -1
  40. package/dist/generated/core/params.gen.d.ts +0 -44
  41. package/dist/generated/core/params.gen.d.ts.map +0 -1
  42. package/dist/generated/core/params.gen.js +0 -105
  43. package/dist/generated/core/params.gen.js.map +0 -1
  44. package/dist/generated/core/pathSerializer.gen.d.ts +0 -34
  45. package/dist/generated/core/pathSerializer.gen.d.ts.map +0 -1
  46. package/dist/generated/core/pathSerializer.gen.js +0 -124
  47. package/dist/generated/core/pathSerializer.gen.js.map +0 -1
  48. package/dist/generated/core/queryKeySerializer.gen.d.ts +0 -19
  49. package/dist/generated/core/queryKeySerializer.gen.d.ts.map +0 -1
  50. package/dist/generated/core/queryKeySerializer.gen.js +0 -106
  51. package/dist/generated/core/queryKeySerializer.gen.js.map +0 -1
  52. package/dist/generated/core/serverSentEvents.gen.d.ts +0 -72
  53. package/dist/generated/core/serverSentEvents.gen.d.ts.map +0 -1
  54. package/dist/generated/core/serverSentEvents.gen.js +0 -140
  55. package/dist/generated/core/serverSentEvents.gen.js.map +0 -1
  56. package/dist/generated/core/types.gen.d.ts +0 -79
  57. package/dist/generated/core/types.gen.d.ts.map +0 -1
  58. package/dist/generated/core/types.gen.js +0 -4
  59. package/dist/generated/core/types.gen.js.map +0 -1
  60. package/dist/generated/core/utils.gen.d.ts +0 -20
  61. package/dist/generated/core/utils.gen.d.ts.map +0 -1
  62. package/dist/generated/core/utils.gen.js +0 -94
  63. package/dist/generated/core/utils.gen.js.map +0 -1
  64. package/dist/generated/index.d.ts +0 -3
  65. package/dist/generated/index.d.ts.map +0 -1
  66. package/dist/generated/index.js +0 -19
  67. package/dist/generated/index.js.map +0 -1
  68. package/dist/generated/sdk.gen.d.ts +0 -433
  69. package/dist/generated/sdk.gen.d.ts.map +0 -1
  70. package/dist/generated/sdk.gen.js +0 -636
  71. package/dist/generated/sdk.gen.js.map +0 -1
  72. package/dist/generated/types.gen.d.ts.map +0 -1
  73. package/dist/generated/types.gen.js +0 -4
  74. package/dist/generated/types.gen.js.map +0 -1
  75. package/dist/src/index.d.ts +0 -310
  76. package/dist/src/index.d.ts.map +0 -1
  77. package/dist/src/index.js +0 -518
  78. package/dist/src/index.js.map +0 -1
package/dist/index.js ADDED
@@ -0,0 +1,1597 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ HindsightClient: () => HindsightClient,
24
+ HindsightError: () => HindsightError,
25
+ createClient: () => createClient,
26
+ createConfig: () => createConfig,
27
+ sdk: () => sdk_gen_exports
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+
31
+ // generated/core/bodySerializer.gen.ts
32
+ var serializeFormDataPair = (data, key, value) => {
33
+ if (typeof value === "string" || value instanceof Blob) {
34
+ data.append(key, value);
35
+ } else if (value instanceof Date) {
36
+ data.append(key, value.toISOString());
37
+ } else {
38
+ data.append(key, JSON.stringify(value));
39
+ }
40
+ };
41
+ var formDataBodySerializer = {
42
+ bodySerializer: (body) => {
43
+ const data = new FormData();
44
+ Object.entries(body).forEach(([key, value]) => {
45
+ if (value === void 0 || value === null) {
46
+ return;
47
+ }
48
+ if (Array.isArray(value)) {
49
+ value.forEach((v) => serializeFormDataPair(data, key, v));
50
+ } else {
51
+ serializeFormDataPair(data, key, value);
52
+ }
53
+ });
54
+ return data;
55
+ }
56
+ };
57
+ var jsonBodySerializer = {
58
+ bodySerializer: (body) => JSON.stringify(
59
+ body,
60
+ (_key, value) => typeof value === "bigint" ? value.toString() : value
61
+ )
62
+ };
63
+
64
+ // generated/core/params.gen.ts
65
+ var extraPrefixesMap = {
66
+ $body_: "body",
67
+ $headers_: "headers",
68
+ $path_: "path",
69
+ $query_: "query"
70
+ };
71
+ var extraPrefixes = Object.entries(extraPrefixesMap);
72
+
73
+ // generated/core/serverSentEvents.gen.ts
74
+ var createSseClient = ({
75
+ onRequest,
76
+ onSseError,
77
+ onSseEvent,
78
+ responseTransformer,
79
+ responseValidator,
80
+ sseDefaultRetryDelay,
81
+ sseMaxRetryAttempts,
82
+ sseMaxRetryDelay,
83
+ sseSleepFn,
84
+ url,
85
+ ...options
86
+ }) => {
87
+ let lastEventId;
88
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
89
+ const createStream = async function* () {
90
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
91
+ let attempt = 0;
92
+ const signal = options.signal ?? new AbortController().signal;
93
+ while (true) {
94
+ if (signal.aborted) break;
95
+ attempt++;
96
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
97
+ if (lastEventId !== void 0) {
98
+ headers.set("Last-Event-ID", lastEventId);
99
+ }
100
+ try {
101
+ const requestInit = {
102
+ redirect: "follow",
103
+ ...options,
104
+ body: options.serializedBody,
105
+ headers,
106
+ signal
107
+ };
108
+ let request = new Request(url, requestInit);
109
+ if (onRequest) {
110
+ request = await onRequest(url, requestInit);
111
+ }
112
+ const _fetch = options.fetch ?? globalThis.fetch;
113
+ const response = await _fetch(request);
114
+ if (!response.ok)
115
+ throw new Error(
116
+ `SSE failed: ${response.status} ${response.statusText}`
117
+ );
118
+ if (!response.body) throw new Error("No body in SSE response");
119
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
120
+ let buffer = "";
121
+ const abortHandler = () => {
122
+ try {
123
+ reader.cancel();
124
+ } catch {
125
+ }
126
+ };
127
+ signal.addEventListener("abort", abortHandler);
128
+ try {
129
+ while (true) {
130
+ const { done, value } = await reader.read();
131
+ if (done) break;
132
+ buffer += value;
133
+ const chunks = buffer.split("\n\n");
134
+ buffer = chunks.pop() ?? "";
135
+ for (const chunk of chunks) {
136
+ const lines = chunk.split("\n");
137
+ const dataLines = [];
138
+ let eventName;
139
+ for (const line of lines) {
140
+ if (line.startsWith("data:")) {
141
+ dataLines.push(line.replace(/^data:\s*/, ""));
142
+ } else if (line.startsWith("event:")) {
143
+ eventName = line.replace(/^event:\s*/, "");
144
+ } else if (line.startsWith("id:")) {
145
+ lastEventId = line.replace(/^id:\s*/, "");
146
+ } else if (line.startsWith("retry:")) {
147
+ const parsed = Number.parseInt(
148
+ line.replace(/^retry:\s*/, ""),
149
+ 10
150
+ );
151
+ if (!Number.isNaN(parsed)) {
152
+ retryDelay = parsed;
153
+ }
154
+ }
155
+ }
156
+ let data;
157
+ let parsedJson = false;
158
+ if (dataLines.length) {
159
+ const rawData = dataLines.join("\n");
160
+ try {
161
+ data = JSON.parse(rawData);
162
+ parsedJson = true;
163
+ } catch {
164
+ data = rawData;
165
+ }
166
+ }
167
+ if (parsedJson) {
168
+ if (responseValidator) {
169
+ await responseValidator(data);
170
+ }
171
+ if (responseTransformer) {
172
+ data = await responseTransformer(data);
173
+ }
174
+ }
175
+ onSseEvent?.({
176
+ data,
177
+ event: eventName,
178
+ id: lastEventId,
179
+ retry: retryDelay
180
+ });
181
+ if (dataLines.length) {
182
+ yield data;
183
+ }
184
+ }
185
+ }
186
+ } finally {
187
+ signal.removeEventListener("abort", abortHandler);
188
+ reader.releaseLock();
189
+ }
190
+ break;
191
+ } catch (error) {
192
+ onSseError?.(error);
193
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
194
+ break;
195
+ }
196
+ const backoff = Math.min(
197
+ retryDelay * 2 ** (attempt - 1),
198
+ sseMaxRetryDelay ?? 3e4
199
+ );
200
+ await sleep(backoff);
201
+ }
202
+ }
203
+ };
204
+ const stream = createStream();
205
+ return { stream };
206
+ };
207
+
208
+ // generated/core/pathSerializer.gen.ts
209
+ var separatorArrayExplode = (style) => {
210
+ switch (style) {
211
+ case "label":
212
+ return ".";
213
+ case "matrix":
214
+ return ";";
215
+ case "simple":
216
+ return ",";
217
+ default:
218
+ return "&";
219
+ }
220
+ };
221
+ var separatorArrayNoExplode = (style) => {
222
+ switch (style) {
223
+ case "form":
224
+ return ",";
225
+ case "pipeDelimited":
226
+ return "|";
227
+ case "spaceDelimited":
228
+ return "%20";
229
+ default:
230
+ return ",";
231
+ }
232
+ };
233
+ var separatorObjectExplode = (style) => {
234
+ switch (style) {
235
+ case "label":
236
+ return ".";
237
+ case "matrix":
238
+ return ";";
239
+ case "simple":
240
+ return ",";
241
+ default:
242
+ return "&";
243
+ }
244
+ };
245
+ var serializeArrayParam = ({
246
+ allowReserved,
247
+ explode,
248
+ name,
249
+ style,
250
+ value
251
+ }) => {
252
+ if (!explode) {
253
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
254
+ switch (style) {
255
+ case "label":
256
+ return `.${joinedValues2}`;
257
+ case "matrix":
258
+ return `;${name}=${joinedValues2}`;
259
+ case "simple":
260
+ return joinedValues2;
261
+ default:
262
+ return `${name}=${joinedValues2}`;
263
+ }
264
+ }
265
+ const separator = separatorArrayExplode(style);
266
+ const joinedValues = value.map((v) => {
267
+ if (style === "label" || style === "simple") {
268
+ return allowReserved ? v : encodeURIComponent(v);
269
+ }
270
+ return serializePrimitiveParam({
271
+ allowReserved,
272
+ name,
273
+ value: v
274
+ });
275
+ }).join(separator);
276
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
277
+ };
278
+ var serializePrimitiveParam = ({
279
+ allowReserved,
280
+ name,
281
+ value
282
+ }) => {
283
+ if (value === void 0 || value === null) {
284
+ return "";
285
+ }
286
+ if (typeof value === "object") {
287
+ throw new Error(
288
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
289
+ );
290
+ }
291
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
292
+ };
293
+ var serializeObjectParam = ({
294
+ allowReserved,
295
+ explode,
296
+ name,
297
+ style,
298
+ value,
299
+ valueOnly
300
+ }) => {
301
+ if (value instanceof Date) {
302
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
303
+ }
304
+ if (style !== "deepObject" && !explode) {
305
+ let values = [];
306
+ Object.entries(value).forEach(([key, v]) => {
307
+ values = [
308
+ ...values,
309
+ key,
310
+ allowReserved ? v : encodeURIComponent(v)
311
+ ];
312
+ });
313
+ const joinedValues2 = values.join(",");
314
+ switch (style) {
315
+ case "form":
316
+ return `${name}=${joinedValues2}`;
317
+ case "label":
318
+ return `.${joinedValues2}`;
319
+ case "matrix":
320
+ return `;${name}=${joinedValues2}`;
321
+ default:
322
+ return joinedValues2;
323
+ }
324
+ }
325
+ const separator = separatorObjectExplode(style);
326
+ const joinedValues = Object.entries(value).map(
327
+ ([key, v]) => serializePrimitiveParam({
328
+ allowReserved,
329
+ name: style === "deepObject" ? `${name}[${key}]` : key,
330
+ value: v
331
+ })
332
+ ).join(separator);
333
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
334
+ };
335
+
336
+ // generated/core/utils.gen.ts
337
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
338
+ var defaultPathSerializer = ({ path, url: _url }) => {
339
+ let url = _url;
340
+ const matches = _url.match(PATH_PARAM_RE);
341
+ if (matches) {
342
+ for (const match of matches) {
343
+ let explode = false;
344
+ let name = match.substring(1, match.length - 1);
345
+ let style = "simple";
346
+ if (name.endsWith("*")) {
347
+ explode = true;
348
+ name = name.substring(0, name.length - 1);
349
+ }
350
+ if (name.startsWith(".")) {
351
+ name = name.substring(1);
352
+ style = "label";
353
+ } else if (name.startsWith(";")) {
354
+ name = name.substring(1);
355
+ style = "matrix";
356
+ }
357
+ const value = path[name];
358
+ if (value === void 0 || value === null) {
359
+ continue;
360
+ }
361
+ if (Array.isArray(value)) {
362
+ url = url.replace(
363
+ match,
364
+ serializeArrayParam({ explode, name, style, value })
365
+ );
366
+ continue;
367
+ }
368
+ if (typeof value === "object") {
369
+ url = url.replace(
370
+ match,
371
+ serializeObjectParam({
372
+ explode,
373
+ name,
374
+ style,
375
+ value,
376
+ valueOnly: true
377
+ })
378
+ );
379
+ continue;
380
+ }
381
+ if (style === "matrix") {
382
+ url = url.replace(
383
+ match,
384
+ `;${serializePrimitiveParam({
385
+ name,
386
+ value
387
+ })}`
388
+ );
389
+ continue;
390
+ }
391
+ const replaceValue = encodeURIComponent(
392
+ style === "label" ? `.${value}` : value
393
+ );
394
+ url = url.replace(match, replaceValue);
395
+ }
396
+ }
397
+ return url;
398
+ };
399
+ var getUrl = ({
400
+ baseUrl,
401
+ path,
402
+ query,
403
+ querySerializer,
404
+ url: _url
405
+ }) => {
406
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
407
+ let url = (baseUrl ?? "") + pathUrl;
408
+ if (path) {
409
+ url = defaultPathSerializer({ path, url });
410
+ }
411
+ let search = query ? querySerializer(query) : "";
412
+ if (search.startsWith("?")) {
413
+ search = search.substring(1);
414
+ }
415
+ if (search) {
416
+ url += `?${search}`;
417
+ }
418
+ return url;
419
+ };
420
+ function getValidRequestBody(options) {
421
+ const hasBody = options.body !== void 0;
422
+ const isSerializedBody = hasBody && options.bodySerializer;
423
+ if (isSerializedBody) {
424
+ if ("serializedBody" in options) {
425
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
426
+ return hasSerializedBody ? options.serializedBody : null;
427
+ }
428
+ return options.body !== "" ? options.body : null;
429
+ }
430
+ if (hasBody) {
431
+ return options.body;
432
+ }
433
+ return void 0;
434
+ }
435
+
436
+ // generated/core/auth.gen.ts
437
+ var getAuthToken = async (auth, callback) => {
438
+ const token = typeof callback === "function" ? await callback(auth) : callback;
439
+ if (!token) {
440
+ return;
441
+ }
442
+ if (auth.scheme === "bearer") {
443
+ return `Bearer ${token}`;
444
+ }
445
+ if (auth.scheme === "basic") {
446
+ return `Basic ${btoa(token)}`;
447
+ }
448
+ return token;
449
+ };
450
+
451
+ // generated/client/utils.gen.ts
452
+ var createQuerySerializer = ({
453
+ parameters = {},
454
+ ...args
455
+ } = {}) => {
456
+ const querySerializer = (queryParams) => {
457
+ const search = [];
458
+ if (queryParams && typeof queryParams === "object") {
459
+ for (const name in queryParams) {
460
+ const value = queryParams[name];
461
+ if (value === void 0 || value === null) {
462
+ continue;
463
+ }
464
+ const options = parameters[name] || args;
465
+ if (Array.isArray(value)) {
466
+ const serializedArray = serializeArrayParam({
467
+ allowReserved: options.allowReserved,
468
+ explode: true,
469
+ name,
470
+ style: "form",
471
+ value,
472
+ ...options.array
473
+ });
474
+ if (serializedArray) search.push(serializedArray);
475
+ } else if (typeof value === "object") {
476
+ const serializedObject = serializeObjectParam({
477
+ allowReserved: options.allowReserved,
478
+ explode: true,
479
+ name,
480
+ style: "deepObject",
481
+ value,
482
+ ...options.object
483
+ });
484
+ if (serializedObject) search.push(serializedObject);
485
+ } else {
486
+ const serializedPrimitive = serializePrimitiveParam({
487
+ allowReserved: options.allowReserved,
488
+ name,
489
+ value
490
+ });
491
+ if (serializedPrimitive) search.push(serializedPrimitive);
492
+ }
493
+ }
494
+ }
495
+ return search.join("&");
496
+ };
497
+ return querySerializer;
498
+ };
499
+ var getParseAs = (contentType) => {
500
+ if (!contentType) {
501
+ return "stream";
502
+ }
503
+ const cleanContent = contentType.split(";")[0]?.trim();
504
+ if (!cleanContent) {
505
+ return;
506
+ }
507
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
508
+ return "json";
509
+ }
510
+ if (cleanContent === "multipart/form-data") {
511
+ return "formData";
512
+ }
513
+ if (["application/", "audio/", "image/", "video/"].some(
514
+ (type) => cleanContent.startsWith(type)
515
+ )) {
516
+ return "blob";
517
+ }
518
+ if (cleanContent.startsWith("text/")) {
519
+ return "text";
520
+ }
521
+ return;
522
+ };
523
+ var checkForExistence = (options, name) => {
524
+ if (!name) {
525
+ return false;
526
+ }
527
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
528
+ return true;
529
+ }
530
+ return false;
531
+ };
532
+ var setAuthParams = async ({
533
+ security,
534
+ ...options
535
+ }) => {
536
+ for (const auth of security) {
537
+ if (checkForExistence(options, auth.name)) {
538
+ continue;
539
+ }
540
+ const token = await getAuthToken(auth, options.auth);
541
+ if (!token) {
542
+ continue;
543
+ }
544
+ const name = auth.name ?? "Authorization";
545
+ switch (auth.in) {
546
+ case "query":
547
+ if (!options.query) {
548
+ options.query = {};
549
+ }
550
+ options.query[name] = token;
551
+ break;
552
+ case "cookie":
553
+ options.headers.append("Cookie", `${name}=${token}`);
554
+ break;
555
+ case "header":
556
+ default:
557
+ options.headers.set(name, token);
558
+ break;
559
+ }
560
+ }
561
+ };
562
+ var buildUrl = (options) => getUrl({
563
+ baseUrl: options.baseUrl,
564
+ path: options.path,
565
+ query: options.query,
566
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
567
+ url: options.url
568
+ });
569
+ var mergeConfigs = (a, b) => {
570
+ const config = { ...a, ...b };
571
+ if (config.baseUrl?.endsWith("/")) {
572
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
573
+ }
574
+ config.headers = mergeHeaders(a.headers, b.headers);
575
+ return config;
576
+ };
577
+ var headersEntries = (headers) => {
578
+ const entries = [];
579
+ headers.forEach((value, key) => {
580
+ entries.push([key, value]);
581
+ });
582
+ return entries;
583
+ };
584
+ var mergeHeaders = (...headers) => {
585
+ const mergedHeaders = new Headers();
586
+ for (const header of headers) {
587
+ if (!header) {
588
+ continue;
589
+ }
590
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
591
+ for (const [key, value] of iterator) {
592
+ if (value === null) {
593
+ mergedHeaders.delete(key);
594
+ } else if (Array.isArray(value)) {
595
+ for (const v of value) {
596
+ mergedHeaders.append(key, v);
597
+ }
598
+ } else if (value !== void 0) {
599
+ mergedHeaders.set(
600
+ key,
601
+ typeof value === "object" ? JSON.stringify(value) : value
602
+ );
603
+ }
604
+ }
605
+ }
606
+ return mergedHeaders;
607
+ };
608
+ var Interceptors = class {
609
+ constructor() {
610
+ this.fns = [];
611
+ }
612
+ clear() {
613
+ this.fns = [];
614
+ }
615
+ eject(id) {
616
+ const index = this.getInterceptorIndex(id);
617
+ if (this.fns[index]) {
618
+ this.fns[index] = null;
619
+ }
620
+ }
621
+ exists(id) {
622
+ const index = this.getInterceptorIndex(id);
623
+ return Boolean(this.fns[index]);
624
+ }
625
+ getInterceptorIndex(id) {
626
+ if (typeof id === "number") {
627
+ return this.fns[id] ? id : -1;
628
+ }
629
+ return this.fns.indexOf(id);
630
+ }
631
+ update(id, fn) {
632
+ const index = this.getInterceptorIndex(id);
633
+ if (this.fns[index]) {
634
+ this.fns[index] = fn;
635
+ return id;
636
+ }
637
+ return false;
638
+ }
639
+ use(fn) {
640
+ this.fns.push(fn);
641
+ return this.fns.length - 1;
642
+ }
643
+ };
644
+ var createInterceptors = () => ({
645
+ error: new Interceptors(),
646
+ request: new Interceptors(),
647
+ response: new Interceptors()
648
+ });
649
+ var defaultQuerySerializer = createQuerySerializer({
650
+ allowReserved: false,
651
+ array: {
652
+ explode: true,
653
+ style: "form"
654
+ },
655
+ object: {
656
+ explode: true,
657
+ style: "deepObject"
658
+ }
659
+ });
660
+ var defaultHeaders = {
661
+ "Content-Type": "application/json"
662
+ };
663
+ var createConfig = (override = {}) => ({
664
+ ...jsonBodySerializer,
665
+ headers: defaultHeaders,
666
+ parseAs: "auto",
667
+ querySerializer: defaultQuerySerializer,
668
+ ...override
669
+ });
670
+
671
+ // generated/client/client.gen.ts
672
+ var createClient = (config = {}) => {
673
+ let _config = mergeConfigs(createConfig(), config);
674
+ const getConfig = () => ({ ..._config });
675
+ const setConfig = (config2) => {
676
+ _config = mergeConfigs(_config, config2);
677
+ return getConfig();
678
+ };
679
+ const interceptors = createInterceptors();
680
+ const beforeRequest = async (options) => {
681
+ const opts = {
682
+ ..._config,
683
+ ...options,
684
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
685
+ headers: mergeHeaders(_config.headers, options.headers),
686
+ serializedBody: void 0
687
+ };
688
+ if (opts.security) {
689
+ await setAuthParams({
690
+ ...opts,
691
+ security: opts.security
692
+ });
693
+ }
694
+ if (opts.requestValidator) {
695
+ await opts.requestValidator(opts);
696
+ }
697
+ if (opts.body !== void 0 && opts.bodySerializer) {
698
+ opts.serializedBody = opts.bodySerializer(opts.body);
699
+ }
700
+ if (opts.body === void 0 || opts.serializedBody === "") {
701
+ opts.headers.delete("Content-Type");
702
+ }
703
+ const url = buildUrl(opts);
704
+ return { opts, url };
705
+ };
706
+ const request = async (options) => {
707
+ const { opts, url } = await beforeRequest(options);
708
+ const { client: _client, ...optsForRequest } = opts;
709
+ const requestInit = {
710
+ redirect: "follow",
711
+ ...optsForRequest,
712
+ body: getValidRequestBody(opts)
713
+ };
714
+ let request2 = new Request(url, requestInit);
715
+ for (const fn of interceptors.request.fns) {
716
+ if (fn) {
717
+ request2 = await fn(request2, opts);
718
+ }
719
+ }
720
+ const _fetch = opts.fetch;
721
+ let response;
722
+ try {
723
+ response = await _fetch(request2);
724
+ } catch (error2) {
725
+ let finalError2 = error2;
726
+ for (const fn of interceptors.error.fns) {
727
+ if (fn) {
728
+ finalError2 = await fn(
729
+ error2,
730
+ void 0,
731
+ request2,
732
+ opts
733
+ );
734
+ }
735
+ }
736
+ finalError2 = finalError2 || {};
737
+ if (opts.throwOnError) {
738
+ throw finalError2;
739
+ }
740
+ return opts.responseStyle === "data" ? void 0 : {
741
+ error: finalError2,
742
+ request: request2,
743
+ response: void 0
744
+ };
745
+ }
746
+ for (const fn of interceptors.response.fns) {
747
+ if (fn) {
748
+ response = await fn(response, request2, opts);
749
+ }
750
+ }
751
+ const result = {
752
+ request: request2,
753
+ response
754
+ };
755
+ if (response.ok) {
756
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
757
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
758
+ let emptyData;
759
+ switch (parseAs) {
760
+ case "arrayBuffer":
761
+ case "blob":
762
+ case "text":
763
+ emptyData = await response[parseAs]();
764
+ break;
765
+ case "formData":
766
+ emptyData = new FormData();
767
+ break;
768
+ case "stream":
769
+ emptyData = response.body;
770
+ break;
771
+ case "json":
772
+ default:
773
+ emptyData = {};
774
+ break;
775
+ }
776
+ return opts.responseStyle === "data" ? emptyData : {
777
+ data: emptyData,
778
+ ...result
779
+ };
780
+ }
781
+ let data;
782
+ switch (parseAs) {
783
+ case "arrayBuffer":
784
+ case "blob":
785
+ case "formData":
786
+ case "json":
787
+ case "text":
788
+ data = await response[parseAs]();
789
+ break;
790
+ case "stream":
791
+ return opts.responseStyle === "data" ? response.body : {
792
+ data: response.body,
793
+ ...result
794
+ };
795
+ }
796
+ if (parseAs === "json") {
797
+ if (opts.responseValidator) {
798
+ await opts.responseValidator(data);
799
+ }
800
+ if (opts.responseTransformer) {
801
+ data = await opts.responseTransformer(data);
802
+ }
803
+ }
804
+ return opts.responseStyle === "data" ? data : {
805
+ data,
806
+ ...result
807
+ };
808
+ }
809
+ const textError = await response.text();
810
+ let jsonError;
811
+ try {
812
+ jsonError = JSON.parse(textError);
813
+ } catch {
814
+ }
815
+ const error = jsonError ?? textError;
816
+ let finalError = error;
817
+ for (const fn of interceptors.error.fns) {
818
+ if (fn) {
819
+ finalError = await fn(error, response, request2, opts);
820
+ }
821
+ }
822
+ finalError = finalError || {};
823
+ if (opts.throwOnError) {
824
+ throw finalError;
825
+ }
826
+ return opts.responseStyle === "data" ? void 0 : {
827
+ error: finalError,
828
+ ...result
829
+ };
830
+ };
831
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
832
+ const makeSseFn = (method) => async (options) => {
833
+ const { opts, url } = await beforeRequest(options);
834
+ return createSseClient({
835
+ ...opts,
836
+ body: opts.body,
837
+ headers: opts.headers,
838
+ method,
839
+ onRequest: async (url2, init) => {
840
+ let request2 = new Request(url2, init);
841
+ for (const fn of interceptors.request.fns) {
842
+ if (fn) {
843
+ request2 = await fn(request2, opts);
844
+ }
845
+ }
846
+ return request2;
847
+ },
848
+ url
849
+ });
850
+ };
851
+ return {
852
+ buildUrl,
853
+ connect: makeMethodFn("CONNECT"),
854
+ delete: makeMethodFn("DELETE"),
855
+ get: makeMethodFn("GET"),
856
+ getConfig,
857
+ head: makeMethodFn("HEAD"),
858
+ interceptors,
859
+ options: makeMethodFn("OPTIONS"),
860
+ patch: makeMethodFn("PATCH"),
861
+ post: makeMethodFn("POST"),
862
+ put: makeMethodFn("PUT"),
863
+ request,
864
+ setConfig,
865
+ sse: {
866
+ connect: makeSseFn("CONNECT"),
867
+ delete: makeSseFn("DELETE"),
868
+ get: makeSseFn("GET"),
869
+ head: makeSseFn("HEAD"),
870
+ options: makeSseFn("OPTIONS"),
871
+ patch: makeSseFn("PATCH"),
872
+ post: makeSseFn("POST"),
873
+ put: makeSseFn("PUT"),
874
+ trace: makeSseFn("TRACE")
875
+ },
876
+ trace: makeMethodFn("TRACE")
877
+ };
878
+ };
879
+
880
+ // generated/sdk.gen.ts
881
+ var sdk_gen_exports = {};
882
+ __export(sdk_gen_exports, {
883
+ addBankBackground: () => addBankBackground,
884
+ cancelOperation: () => cancelOperation,
885
+ clearBankMemories: () => clearBankMemories,
886
+ clearMemoryObservations: () => clearMemoryObservations,
887
+ clearObservations: () => clearObservations,
888
+ createDirective: () => createDirective,
889
+ createMentalModel: () => createMentalModel,
890
+ createOrUpdateBank: () => createOrUpdateBank,
891
+ createWebhook: () => createWebhook,
892
+ deleteBank: () => deleteBank,
893
+ deleteDirective: () => deleteDirective,
894
+ deleteDocument: () => deleteDocument,
895
+ deleteMentalModel: () => deleteMentalModel,
896
+ deleteWebhook: () => deleteWebhook,
897
+ fileRetain: () => fileRetain,
898
+ getAgentStats: () => getAgentStats,
899
+ getBankConfig: () => getBankConfig,
900
+ getBankProfile: () => getBankProfile,
901
+ getChunk: () => getChunk,
902
+ getDirective: () => getDirective,
903
+ getDocument: () => getDocument,
904
+ getEntity: () => getEntity,
905
+ getGraph: () => getGraph,
906
+ getMemory: () => getMemory,
907
+ getMentalModel: () => getMentalModel,
908
+ getMentalModelHistory: () => getMentalModelHistory,
909
+ getObservationHistory: () => getObservationHistory,
910
+ getOperationStatus: () => getOperationStatus,
911
+ getVersion: () => getVersion,
912
+ healthEndpointHealthGet: () => healthEndpointHealthGet,
913
+ listBanks: () => listBanks,
914
+ listDirectives: () => listDirectives,
915
+ listDocuments: () => listDocuments,
916
+ listEntities: () => listEntities,
917
+ listMemories: () => listMemories,
918
+ listMentalModels: () => listMentalModels,
919
+ listOperations: () => listOperations,
920
+ listTags: () => listTags,
921
+ listWebhookDeliveries: () => listWebhookDeliveries,
922
+ listWebhooks: () => listWebhooks,
923
+ metricsEndpointMetricsGet: () => metricsEndpointMetricsGet,
924
+ recallMemories: () => recallMemories,
925
+ recoverConsolidation: () => recoverConsolidation,
926
+ reflect: () => reflect,
927
+ refreshMentalModel: () => refreshMentalModel,
928
+ regenerateEntityObservations: () => regenerateEntityObservations,
929
+ resetBankConfig: () => resetBankConfig,
930
+ retainMemories: () => retainMemories,
931
+ retryOperation: () => retryOperation,
932
+ triggerConsolidation: () => triggerConsolidation,
933
+ updateBank: () => updateBank,
934
+ updateBankConfig: () => updateBankConfig,
935
+ updateBankDisposition: () => updateBankDisposition,
936
+ updateDirective: () => updateDirective,
937
+ updateDocument: () => updateDocument,
938
+ updateMentalModel: () => updateMentalModel,
939
+ updateWebhook: () => updateWebhook
940
+ });
941
+
942
+ // generated/client.gen.ts
943
+ var client = createClient(createConfig());
944
+
945
+ // generated/sdk.gen.ts
946
+ var healthEndpointHealthGet = (options) => (options?.client ?? client).get({ url: "/health", ...options });
947
+ var getVersion = (options) => (options?.client ?? client).get({
948
+ url: "/version",
949
+ ...options
950
+ });
951
+ var metricsEndpointMetricsGet = (options) => (options?.client ?? client).get({ url: "/metrics", ...options });
952
+ var getGraph = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/graph", ...options });
953
+ var listMemories = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/memories/list", ...options });
954
+ var getMemory = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/memories/{memory_id}", ...options });
955
+ var getObservationHistory = (options) => (options.client ?? client).get({
956
+ url: "/v1/default/banks/{bank_id}/memories/{memory_id}/history",
957
+ ...options
958
+ });
959
+ var recallMemories = (options) => (options.client ?? client).post({
960
+ url: "/v1/default/banks/{bank_id}/memories/recall",
961
+ ...options,
962
+ headers: {
963
+ "Content-Type": "application/json",
964
+ ...options.headers
965
+ }
966
+ });
967
+ var reflect = (options) => (options.client ?? client).post({
968
+ url: "/v1/default/banks/{bank_id}/reflect",
969
+ ...options,
970
+ headers: {
971
+ "Content-Type": "application/json",
972
+ ...options.headers
973
+ }
974
+ });
975
+ var listBanks = (options) => (options?.client ?? client).get({ url: "/v1/default/banks", ...options });
976
+ var getAgentStats = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/stats", ...options });
977
+ var listEntities = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/entities", ...options });
978
+ var getEntity = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/entities/{entity_id}", ...options });
979
+ var regenerateEntityObservations = (options) => (options.client ?? client).post({
980
+ url: "/v1/default/banks/{bank_id}/entities/{entity_id}/regenerate",
981
+ ...options
982
+ });
983
+ var listMentalModels = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/mental-models", ...options });
984
+ var createMentalModel = (options) => (options.client ?? client).post({
985
+ url: "/v1/default/banks/{bank_id}/mental-models",
986
+ ...options,
987
+ headers: {
988
+ "Content-Type": "application/json",
989
+ ...options.headers
990
+ }
991
+ });
992
+ var deleteMentalModel = (options) => (options.client ?? client).delete({
993
+ url: "/v1/default/banks/{bank_id}/mental-models/{mental_model_id}",
994
+ ...options
995
+ });
996
+ var getMentalModel = (options) => (options.client ?? client).get({
997
+ url: "/v1/default/banks/{bank_id}/mental-models/{mental_model_id}",
998
+ ...options
999
+ });
1000
+ var updateMentalModel = (options) => (options.client ?? client).patch({
1001
+ url: "/v1/default/banks/{bank_id}/mental-models/{mental_model_id}",
1002
+ ...options,
1003
+ headers: {
1004
+ "Content-Type": "application/json",
1005
+ ...options.headers
1006
+ }
1007
+ });
1008
+ var getMentalModelHistory = (options) => (options.client ?? client).get({
1009
+ url: "/v1/default/banks/{bank_id}/mental-models/{mental_model_id}/history",
1010
+ ...options
1011
+ });
1012
+ var refreshMentalModel = (options) => (options.client ?? client).post({
1013
+ url: "/v1/default/banks/{bank_id}/mental-models/{mental_model_id}/refresh",
1014
+ ...options
1015
+ });
1016
+ var listDirectives = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/directives", ...options });
1017
+ var createDirective = (options) => (options.client ?? client).post({
1018
+ url: "/v1/default/banks/{bank_id}/directives",
1019
+ ...options,
1020
+ headers: {
1021
+ "Content-Type": "application/json",
1022
+ ...options.headers
1023
+ }
1024
+ });
1025
+ var deleteDirective = (options) => (options.client ?? client).delete({
1026
+ url: "/v1/default/banks/{bank_id}/directives/{directive_id}",
1027
+ ...options
1028
+ });
1029
+ var getDirective = (options) => (options.client ?? client).get({
1030
+ url: "/v1/default/banks/{bank_id}/directives/{directive_id}",
1031
+ ...options
1032
+ });
1033
+ var updateDirective = (options) => (options.client ?? client).patch({
1034
+ url: "/v1/default/banks/{bank_id}/directives/{directive_id}",
1035
+ ...options,
1036
+ headers: {
1037
+ "Content-Type": "application/json",
1038
+ ...options.headers
1039
+ }
1040
+ });
1041
+ var listDocuments = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/documents", ...options });
1042
+ var deleteDocument = (options) => (options.client ?? client).delete({ url: "/v1/default/banks/{bank_id}/documents/{document_id}", ...options });
1043
+ var getDocument = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/documents/{document_id}", ...options });
1044
+ var updateDocument = (options) => (options.client ?? client).patch({
1045
+ url: "/v1/default/banks/{bank_id}/documents/{document_id}",
1046
+ ...options,
1047
+ headers: {
1048
+ "Content-Type": "application/json",
1049
+ ...options.headers
1050
+ }
1051
+ });
1052
+ var listTags = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/tags", ...options });
1053
+ var getChunk = (options) => (options.client ?? client).get({ url: "/v1/default/chunks/{chunk_id}", ...options });
1054
+ var listOperations = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/operations", ...options });
1055
+ var cancelOperation = (options) => (options.client ?? client).delete({
1056
+ url: "/v1/default/banks/{bank_id}/operations/{operation_id}",
1057
+ ...options
1058
+ });
1059
+ var getOperationStatus = (options) => (options.client ?? client).get({
1060
+ url: "/v1/default/banks/{bank_id}/operations/{operation_id}",
1061
+ ...options
1062
+ });
1063
+ var retryOperation = (options) => (options.client ?? client).post({
1064
+ url: "/v1/default/banks/{bank_id}/operations/{operation_id}/retry",
1065
+ ...options
1066
+ });
1067
+ var getBankProfile = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/profile", ...options });
1068
+ var updateBankDisposition = (options) => (options.client ?? client).put({
1069
+ url: "/v1/default/banks/{bank_id}/profile",
1070
+ ...options,
1071
+ headers: {
1072
+ "Content-Type": "application/json",
1073
+ ...options.headers
1074
+ }
1075
+ });
1076
+ var addBankBackground = (options) => (options.client ?? client).post({
1077
+ url: "/v1/default/banks/{bank_id}/background",
1078
+ ...options,
1079
+ headers: {
1080
+ "Content-Type": "application/json",
1081
+ ...options.headers
1082
+ }
1083
+ });
1084
+ var deleteBank = (options) => (options.client ?? client).delete({ url: "/v1/default/banks/{bank_id}", ...options });
1085
+ var updateBank = (options) => (options.client ?? client).patch({
1086
+ url: "/v1/default/banks/{bank_id}",
1087
+ ...options,
1088
+ headers: {
1089
+ "Content-Type": "application/json",
1090
+ ...options.headers
1091
+ }
1092
+ });
1093
+ var createOrUpdateBank = (options) => (options.client ?? client).put({
1094
+ url: "/v1/default/banks/{bank_id}",
1095
+ ...options,
1096
+ headers: {
1097
+ "Content-Type": "application/json",
1098
+ ...options.headers
1099
+ }
1100
+ });
1101
+ var clearObservations = (options) => (options.client ?? client).delete({ url: "/v1/default/banks/{bank_id}/observations", ...options });
1102
+ var recoverConsolidation = (options) => (options.client ?? client).post({ url: "/v1/default/banks/{bank_id}/consolidation/recover", ...options });
1103
+ var clearMemoryObservations = (options) => (options.client ?? client).delete({
1104
+ url: "/v1/default/banks/{bank_id}/memories/{memory_id}/observations",
1105
+ ...options
1106
+ });
1107
+ var resetBankConfig = (options) => (options.client ?? client).delete({ url: "/v1/default/banks/{bank_id}/config", ...options });
1108
+ var getBankConfig = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/config", ...options });
1109
+ var updateBankConfig = (options) => (options.client ?? client).patch({
1110
+ url: "/v1/default/banks/{bank_id}/config",
1111
+ ...options,
1112
+ headers: {
1113
+ "Content-Type": "application/json",
1114
+ ...options.headers
1115
+ }
1116
+ });
1117
+ var triggerConsolidation = (options) => (options.client ?? client).post({ url: "/v1/default/banks/{bank_id}/consolidate", ...options });
1118
+ var listWebhooks = (options) => (options.client ?? client).get({ url: "/v1/default/banks/{bank_id}/webhooks", ...options });
1119
+ var createWebhook = (options) => (options.client ?? client).post({
1120
+ url: "/v1/default/banks/{bank_id}/webhooks",
1121
+ ...options,
1122
+ headers: {
1123
+ "Content-Type": "application/json",
1124
+ ...options.headers
1125
+ }
1126
+ });
1127
+ var deleteWebhook = (options) => (options.client ?? client).delete({ url: "/v1/default/banks/{bank_id}/webhooks/{webhook_id}", ...options });
1128
+ var updateWebhook = (options) => (options.client ?? client).patch({
1129
+ url: "/v1/default/banks/{bank_id}/webhooks/{webhook_id}",
1130
+ ...options,
1131
+ headers: {
1132
+ "Content-Type": "application/json",
1133
+ ...options.headers
1134
+ }
1135
+ });
1136
+ var listWebhookDeliveries = (options) => (options.client ?? client).get({
1137
+ url: "/v1/default/banks/{bank_id}/webhooks/{webhook_id}/deliveries",
1138
+ ...options
1139
+ });
1140
+ var clearBankMemories = (options) => (options.client ?? client).delete({ url: "/v1/default/banks/{bank_id}/memories", ...options });
1141
+ var retainMemories = (options) => (options.client ?? client).post({
1142
+ url: "/v1/default/banks/{bank_id}/memories",
1143
+ ...options,
1144
+ headers: {
1145
+ "Content-Type": "application/json",
1146
+ ...options.headers
1147
+ }
1148
+ });
1149
+ var fileRetain = (options) => (options.client ?? client).post({
1150
+ ...formDataBodySerializer,
1151
+ url: "/v1/default/banks/{bank_id}/files/retain",
1152
+ ...options,
1153
+ headers: {
1154
+ "Content-Type": null,
1155
+ ...options.headers
1156
+ }
1157
+ });
1158
+
1159
+ // src/index.ts
1160
+ var HindsightError = class extends Error {
1161
+ constructor(message, statusCode, details) {
1162
+ super(message);
1163
+ this.name = "HindsightError";
1164
+ this.statusCode = statusCode;
1165
+ this.details = details;
1166
+ }
1167
+ };
1168
+ var HindsightClient = class {
1169
+ constructor(options) {
1170
+ this.client = createClient(
1171
+ createConfig({
1172
+ baseUrl: options.baseUrl,
1173
+ headers: options.apiKey ? { Authorization: `Bearer ${options.apiKey}` } : void 0
1174
+ })
1175
+ );
1176
+ }
1177
+ /**
1178
+ * Validates the API response and throws an error if the request failed.
1179
+ */
1180
+ validateResponse(response, operation) {
1181
+ if (!response.data) {
1182
+ const error = response.error;
1183
+ const httpResponse = response.response;
1184
+ const statusCode = httpResponse?.status;
1185
+ const details = error?.detail || error?.message || error;
1186
+ throw new HindsightError(
1187
+ `${operation} failed: ${JSON.stringify(details)}`,
1188
+ statusCode,
1189
+ details
1190
+ );
1191
+ }
1192
+ return response.data;
1193
+ }
1194
+ /**
1195
+ * Retain a single memory for a bank.
1196
+ */
1197
+ async retain(bankId, content, options) {
1198
+ const item = { content };
1199
+ if (options?.timestamp) {
1200
+ item.timestamp = options.timestamp instanceof Date ? options.timestamp.toISOString() : options.timestamp;
1201
+ }
1202
+ if (options?.context) {
1203
+ item.context = options.context;
1204
+ }
1205
+ if (options?.metadata) {
1206
+ item.metadata = options.metadata;
1207
+ }
1208
+ if (options?.documentId) {
1209
+ item.document_id = options.documentId;
1210
+ }
1211
+ if (options?.entities) {
1212
+ item.entities = options.entities;
1213
+ }
1214
+ if (options?.tags) {
1215
+ item.tags = options.tags;
1216
+ }
1217
+ const response = await retainMemories({
1218
+ client: this.client,
1219
+ path: { bank_id: bankId },
1220
+ body: { items: [item], async: options?.async }
1221
+ });
1222
+ return this.validateResponse(response, "retain");
1223
+ }
1224
+ /**
1225
+ * Retain multiple memories in batch.
1226
+ */
1227
+ async retainBatch(bankId, items, options) {
1228
+ const processedItems = items.map((item) => ({
1229
+ content: item.content,
1230
+ context: item.context,
1231
+ metadata: item.metadata,
1232
+ document_id: item.document_id,
1233
+ entities: item.entities,
1234
+ tags: item.tags,
1235
+ observation_scopes: item.observation_scopes,
1236
+ strategy: item.strategy,
1237
+ timestamp: item.timestamp instanceof Date ? item.timestamp.toISOString() : item.timestamp
1238
+ }));
1239
+ const itemsWithDocId = processedItems.map((item) => ({
1240
+ ...item,
1241
+ document_id: item.document_id || options?.documentId
1242
+ }));
1243
+ const response = await retainMemories({
1244
+ client: this.client,
1245
+ path: { bank_id: bankId },
1246
+ body: {
1247
+ items: itemsWithDocId,
1248
+ document_tags: options?.documentTags,
1249
+ async: options?.async
1250
+ }
1251
+ });
1252
+ return this.validateResponse(response, "retainBatch");
1253
+ }
1254
+ /**
1255
+ * Upload files and retain their contents as memories.
1256
+ *
1257
+ * Files are automatically converted to text (PDF, DOCX, images via OCR, audio via
1258
+ * transcription, and more) and ingested as memories. Processing is always asynchronous —
1259
+ * use the returned operation IDs to track progress via the operations endpoint.
1260
+ *
1261
+ * @param bankId - The memory bank ID
1262
+ * @param files - Array of File or Blob objects to upload
1263
+ * @param options - Optional settings: context, documentTags, filesMetadata
1264
+ */
1265
+ async retainFiles(bankId, files, options) {
1266
+ const meta = options?.filesMetadata ?? files.map(() => options?.context ? { context: options.context } : {});
1267
+ const requestBody = JSON.stringify({
1268
+ files_metadata: meta
1269
+ });
1270
+ const response = await fileRetain({
1271
+ client: this.client,
1272
+ path: { bank_id: bankId },
1273
+ body: { files, request: requestBody }
1274
+ });
1275
+ return this.validateResponse(response, "retainFiles");
1276
+ }
1277
+ /**
1278
+ * Recall memories with a natural language query.
1279
+ */
1280
+ async recall(bankId, query, options) {
1281
+ const response = await recallMemories({
1282
+ client: this.client,
1283
+ path: { bank_id: bankId },
1284
+ body: {
1285
+ query,
1286
+ types: options?.types,
1287
+ max_tokens: options?.maxTokens,
1288
+ budget: options?.budget || "mid",
1289
+ trace: options?.trace,
1290
+ query_timestamp: options?.queryTimestamp,
1291
+ include: {
1292
+ entities: options?.includeEntities === false ? null : options?.includeEntities ? { max_tokens: options?.maxEntityTokens ?? 500 } : void 0,
1293
+ chunks: options?.includeChunks ? { max_tokens: options?.maxChunkTokens ?? 8192 } : void 0,
1294
+ source_facts: options?.includeSourceFacts ? { max_tokens: options?.maxSourceFactsTokens ?? 4096 } : void 0
1295
+ },
1296
+ tags: options?.tags,
1297
+ tags_match: options?.tagsMatch
1298
+ }
1299
+ });
1300
+ return this.validateResponse(response, "recall");
1301
+ }
1302
+ /**
1303
+ * Reflect and generate a contextual answer using the bank's identity and memories.
1304
+ */
1305
+ async reflect(bankId, query, options) {
1306
+ const response = await reflect({
1307
+ client: this.client,
1308
+ path: { bank_id: bankId },
1309
+ body: {
1310
+ query,
1311
+ context: options?.context,
1312
+ budget: options?.budget || "low",
1313
+ tags: options?.tags,
1314
+ tags_match: options?.tagsMatch
1315
+ }
1316
+ });
1317
+ return this.validateResponse(response, "reflect");
1318
+ }
1319
+ /**
1320
+ * List memories with pagination.
1321
+ */
1322
+ async listMemories(bankId, options) {
1323
+ const response = await listMemories({
1324
+ client: this.client,
1325
+ path: { bank_id: bankId },
1326
+ query: {
1327
+ limit: options?.limit,
1328
+ offset: options?.offset,
1329
+ type: options?.type,
1330
+ q: options?.q
1331
+ }
1332
+ });
1333
+ return this.validateResponse(response, "listMemories");
1334
+ }
1335
+ /**
1336
+ * Create or update a bank with disposition, missions, and operational configuration.
1337
+ */
1338
+ async createBank(bankId, options = {}) {
1339
+ const response = await createOrUpdateBank({
1340
+ client: this.client,
1341
+ path: { bank_id: bankId },
1342
+ body: {
1343
+ name: options.name,
1344
+ mission: options.mission,
1345
+ reflect_mission: options.reflectMission,
1346
+ background: options.background,
1347
+ disposition: options.disposition,
1348
+ disposition_skepticism: options.dispositionSkepticism,
1349
+ disposition_literalism: options.dispositionLiteralism,
1350
+ disposition_empathy: options.dispositionEmpathy,
1351
+ retain_mission: options.retainMission,
1352
+ retain_extraction_mode: options.retainExtractionMode,
1353
+ retain_custom_instructions: options.retainCustomInstructions,
1354
+ retain_chunk_size: options.retainChunkSize,
1355
+ enable_observations: options.enableObservations,
1356
+ observations_mission: options.observationsMission
1357
+ }
1358
+ });
1359
+ return this.validateResponse(response, "createBank");
1360
+ }
1361
+ /**
1362
+ * Set or update the reflect mission for a memory bank.
1363
+ * @deprecated Use createBank({ reflectMission: '...' }) instead.
1364
+ */
1365
+ async setMission(bankId, mission) {
1366
+ return this.createBank(bankId, { reflectMission: mission });
1367
+ }
1368
+ /**
1369
+ * Get a bank's profile.
1370
+ */
1371
+ async getBankProfile(bankId) {
1372
+ const response = await getBankProfile({
1373
+ client: this.client,
1374
+ path: { bank_id: bankId }
1375
+ });
1376
+ return this.validateResponse(response, "getBankProfile");
1377
+ }
1378
+ /**
1379
+ * Get the resolved configuration for a bank, including any bank-level overrides.
1380
+ *
1381
+ * Can be disabled on the server by setting `HINDSIGHT_API_ENABLE_BANK_CONFIG_API=false`.
1382
+ */
1383
+ async getBankConfig(bankId) {
1384
+ const response = await getBankConfig({
1385
+ client: this.client,
1386
+ path: { bank_id: bankId }
1387
+ });
1388
+ return this.validateResponse(response, "getBankConfig");
1389
+ }
1390
+ /**
1391
+ * Update configuration overrides for a bank.
1392
+ *
1393
+ * Can be disabled on the server by setting `HINDSIGHT_API_ENABLE_BANK_CONFIG_API=false`.
1394
+ *
1395
+ * @param bankId - The memory bank ID
1396
+ * @param options - Fields to override
1397
+ */
1398
+ async updateBankConfig(bankId, options) {
1399
+ const updates = {};
1400
+ if (options.reflectMission !== void 0) updates.reflect_mission = options.reflectMission;
1401
+ if (options.retainMission !== void 0) updates.retain_mission = options.retainMission;
1402
+ if (options.retainExtractionMode !== void 0) updates.retain_extraction_mode = options.retainExtractionMode;
1403
+ if (options.retainCustomInstructions !== void 0)
1404
+ updates.retain_custom_instructions = options.retainCustomInstructions;
1405
+ if (options.retainChunkSize !== void 0) updates.retain_chunk_size = options.retainChunkSize;
1406
+ if (options.enableObservations !== void 0) updates.enable_observations = options.enableObservations;
1407
+ if (options.observationsMission !== void 0) updates.observations_mission = options.observationsMission;
1408
+ if (options.dispositionSkepticism !== void 0) updates.disposition_skepticism = options.dispositionSkepticism;
1409
+ if (options.dispositionLiteralism !== void 0) updates.disposition_literalism = options.dispositionLiteralism;
1410
+ if (options.dispositionEmpathy !== void 0) updates.disposition_empathy = options.dispositionEmpathy;
1411
+ const response = await updateBankConfig({
1412
+ client: this.client,
1413
+ path: { bank_id: bankId },
1414
+ body: { updates }
1415
+ });
1416
+ return this.validateResponse(response, "updateBankConfig");
1417
+ }
1418
+ /**
1419
+ * Reset all bank-level configuration overrides, reverting to server defaults.
1420
+ *
1421
+ * Can be disabled on the server by setting `HINDSIGHT_API_ENABLE_BANK_CONFIG_API=false`.
1422
+ */
1423
+ async resetBankConfig(bankId) {
1424
+ const response = await resetBankConfig({
1425
+ client: this.client,
1426
+ path: { bank_id: bankId }
1427
+ });
1428
+ return this.validateResponse(response, "resetBankConfig");
1429
+ }
1430
+ /**
1431
+ * Delete a bank.
1432
+ */
1433
+ async deleteBank(bankId) {
1434
+ const response = await deleteBank({
1435
+ client: this.client,
1436
+ path: { bank_id: bankId }
1437
+ });
1438
+ if (response.error) {
1439
+ throw new Error(`deleteBank failed: ${JSON.stringify(response.error)}`);
1440
+ }
1441
+ }
1442
+ // Directive methods
1443
+ /**
1444
+ * Create a directive (hard rule for reflect).
1445
+ */
1446
+ async createDirective(bankId, name, content, options) {
1447
+ const response = await createDirective({
1448
+ client: this.client,
1449
+ path: { bank_id: bankId },
1450
+ body: {
1451
+ name,
1452
+ content,
1453
+ priority: options?.priority ?? 0,
1454
+ is_active: options?.isActive ?? true,
1455
+ tags: options?.tags
1456
+ }
1457
+ });
1458
+ return this.validateResponse(response, "createDirective");
1459
+ }
1460
+ /**
1461
+ * List all directives in a bank.
1462
+ */
1463
+ async listDirectives(bankId, options) {
1464
+ const response = await listDirectives({
1465
+ client: this.client,
1466
+ path: { bank_id: bankId },
1467
+ query: { tags: options?.tags }
1468
+ });
1469
+ return this.validateResponse(response, "listDirectives");
1470
+ }
1471
+ /**
1472
+ * Get a specific directive.
1473
+ */
1474
+ async getDirective(bankId, directiveId) {
1475
+ const response = await getDirective({
1476
+ client: this.client,
1477
+ path: { bank_id: bankId, directive_id: directiveId }
1478
+ });
1479
+ return this.validateResponse(response, "getDirective");
1480
+ }
1481
+ /**
1482
+ * Update a directive.
1483
+ */
1484
+ async updateDirective(bankId, directiveId, options) {
1485
+ const response = await updateDirective({
1486
+ client: this.client,
1487
+ path: { bank_id: bankId, directive_id: directiveId },
1488
+ body: {
1489
+ name: options.name,
1490
+ content: options.content,
1491
+ priority: options.priority,
1492
+ is_active: options.isActive,
1493
+ tags: options.tags
1494
+ }
1495
+ });
1496
+ return this.validateResponse(response, "updateDirective");
1497
+ }
1498
+ /**
1499
+ * Delete a directive.
1500
+ */
1501
+ async deleteDirective(bankId, directiveId) {
1502
+ const response = await deleteDirective({
1503
+ client: this.client,
1504
+ path: { bank_id: bankId, directive_id: directiveId }
1505
+ });
1506
+ if (response.error) {
1507
+ throw new Error(`deleteDirective failed: ${JSON.stringify(response.error)}`);
1508
+ }
1509
+ }
1510
+ // Mental Model methods
1511
+ /**
1512
+ * Create a mental model (runs reflect in background).
1513
+ */
1514
+ async createMentalModel(bankId, name, sourceQuery, options) {
1515
+ const response = await createMentalModel({
1516
+ client: this.client,
1517
+ path: { bank_id: bankId },
1518
+ body: {
1519
+ name,
1520
+ source_query: sourceQuery,
1521
+ tags: options?.tags,
1522
+ max_tokens: options?.maxTokens,
1523
+ trigger: options?.trigger ? { refresh_after_consolidation: options.trigger.refreshAfterConsolidation } : void 0
1524
+ }
1525
+ });
1526
+ return this.validateResponse(response, "createMentalModel");
1527
+ }
1528
+ /**
1529
+ * List all mental models in a bank.
1530
+ */
1531
+ async listMentalModels(bankId, options) {
1532
+ const response = await listMentalModels({
1533
+ client: this.client,
1534
+ path: { bank_id: bankId },
1535
+ query: { tags: options?.tags }
1536
+ });
1537
+ return this.validateResponse(response, "listMentalModels");
1538
+ }
1539
+ /**
1540
+ * Get a specific mental model.
1541
+ */
1542
+ async getMentalModel(bankId, mentalModelId) {
1543
+ const response = await getMentalModel({
1544
+ client: this.client,
1545
+ path: { bank_id: bankId, mental_model_id: mentalModelId }
1546
+ });
1547
+ return this.validateResponse(response, "getMentalModel");
1548
+ }
1549
+ /**
1550
+ * Refresh a mental model to update with current knowledge.
1551
+ */
1552
+ async refreshMentalModel(bankId, mentalModelId) {
1553
+ const response = await refreshMentalModel({
1554
+ client: this.client,
1555
+ path: { bank_id: bankId, mental_model_id: mentalModelId }
1556
+ });
1557
+ return this.validateResponse(response, "refreshMentalModel");
1558
+ }
1559
+ /**
1560
+ * Update a mental model's metadata.
1561
+ */
1562
+ async updateMentalModel(bankId, mentalModelId, options) {
1563
+ const response = await updateMentalModel({
1564
+ client: this.client,
1565
+ path: { bank_id: bankId, mental_model_id: mentalModelId },
1566
+ body: {
1567
+ name: options.name,
1568
+ source_query: options.sourceQuery,
1569
+ tags: options.tags,
1570
+ max_tokens: options.maxTokens,
1571
+ trigger: options.trigger ? { refresh_after_consolidation: options.trigger.refreshAfterConsolidation } : void 0
1572
+ }
1573
+ });
1574
+ return this.validateResponse(response, "updateMentalModel");
1575
+ }
1576
+ /**
1577
+ * Delete a mental model.
1578
+ */
1579
+ async deleteMentalModel(bankId, mentalModelId) {
1580
+ const response = await deleteMentalModel({
1581
+ client: this.client,
1582
+ path: { bank_id: bankId, mental_model_id: mentalModelId }
1583
+ });
1584
+ if (response.error) {
1585
+ throw new Error(`deleteMentalModel failed: ${JSON.stringify(response.error)}`);
1586
+ }
1587
+ }
1588
+ };
1589
+ // Annotate the CommonJS export names for ESM import in node:
1590
+ 0 && (module.exports = {
1591
+ HindsightClient,
1592
+ HindsightError,
1593
+ createClient,
1594
+ createConfig,
1595
+ sdk
1596
+ });
1597
+ //# sourceMappingURL=index.js.map