hebbrix 2.2.0 → 2.3.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 CHANGED
@@ -25,7 +25,9 @@ __export(index_exports, {
25
25
  CollectionsResource: () => CollectionsResource,
26
26
  ConsolidationResource: () => ConsolidationResource,
27
27
  CorrectionsResource: () => CorrectionsResource,
28
+ EntitlementError: () => EntitlementError,
28
29
  HebbrixError: () => HebbrixError,
30
+ IndexingTimeoutError: () => IndexingTimeoutError,
29
31
  MemoriesResource: () => MemoriesResource,
30
32
  MemoryClient: () => MemoryClient,
31
33
  MemoryJobsResource: () => MemoryJobsResource,
@@ -40,7 +42,6 @@ __export(index_exports, {
40
42
  TemporalResource: () => TemporalResource,
41
43
  ValidationError: () => ValidationError,
42
44
  WorkingMemoryResource: () => WorkingMemoryResource,
43
- WorldModelResource: () => WorldModelResource,
44
45
  enforceSearchSafety: () => enforceSearchSafety
45
46
  });
46
47
  module.exports = __toCommonJS(index_exports);
@@ -81,7 +82,7 @@ function enforceSearchSafety(response, rowsKey = "results") {
81
82
  reason = "no_match_contains_evidence";
82
83
  }
83
84
  }
84
- if (reason || data.degraded === true || data.no_match === true || data.abstain_recommended === true) {
85
+ if (reason || data.no_match === true) {
85
86
  data[rowsKey] = [];
86
87
  if (rowsKey === "results") data.total = 0;
87
88
  data.no_match = true;
@@ -93,10 +94,78 @@ function enforceSearchSafety(response, rowsKey = "results") {
93
94
  data.sdk_safety_reason = reason;
94
95
  data.grounding = { status: "no_grounded_match", reason };
95
96
  }
97
+ } else if (data.degraded === true || data.abstain_recommended === true) {
98
+ data.sdk_safety_reason = "degraded_evidence_preserved";
96
99
  }
97
100
  return data;
98
101
  }
99
102
 
103
+ // src/errors.ts
104
+ var HebbrixError = class _HebbrixError extends Error {
105
+ constructor(message, statusCode, options = {}) {
106
+ super(message);
107
+ this.name = "HebbrixError";
108
+ this.statusCode = statusCode;
109
+ this.code = options.code;
110
+ this.requestId = options.requestId;
111
+ this.details = options.details;
112
+ Object.setPrototypeOf(this, _HebbrixError.prototype);
113
+ }
114
+ };
115
+ var EntitlementError = class _EntitlementError extends HebbrixError {
116
+ constructor(message, statusCode, options = {}) {
117
+ super(message, statusCode, options);
118
+ this.name = "EntitlementError";
119
+ Object.setPrototypeOf(this, _EntitlementError.prototype);
120
+ }
121
+ };
122
+ var IndexingTimeoutError = class _IndexingTimeoutError extends Error {
123
+ constructor(message, receipt) {
124
+ super(message);
125
+ this.name = "IndexingTimeoutError";
126
+ this.receipt = { ...receipt };
127
+ this.memoryIds = [...receipt.memory_ids || []];
128
+ this.statusUrl = receipt.status_url;
129
+ Object.setPrototypeOf(this, _IndexingTimeoutError.prototype);
130
+ }
131
+ };
132
+ var AuthenticationError = class _AuthenticationError extends HebbrixError {
133
+ constructor(message = "Authentication failed", options = {}) {
134
+ super(message, 401, options);
135
+ this.name = "AuthenticationError";
136
+ Object.setPrototypeOf(this, _AuthenticationError.prototype);
137
+ }
138
+ };
139
+ var ValidationError = class _ValidationError extends HebbrixError {
140
+ constructor(message, errors, options = {}) {
141
+ super(message, 422, options);
142
+ this.name = "ValidationError";
143
+ this.errors = errors;
144
+ Object.setPrototypeOf(this, _ValidationError.prototype);
145
+ }
146
+ };
147
+ var NotFoundError = class _NotFoundError extends HebbrixError {
148
+ constructor(message = "Resource not found", options = {}) {
149
+ super(message, 404, options);
150
+ this.name = "NotFoundError";
151
+ Object.setPrototypeOf(this, _NotFoundError.prototype);
152
+ }
153
+ };
154
+ var RateLimitError = class _RateLimitError extends HebbrixError {
155
+ constructor(message = "Rate limit exceeded", options = {}) {
156
+ super(message, 429, options);
157
+ this.name = "RateLimitError";
158
+ Object.setPrototypeOf(this, _RateLimitError.prototype);
159
+ }
160
+ };
161
+ var ServerError = class _ServerError extends HebbrixError {
162
+ constructor(message = "Internal server error", options = {}) {
163
+ super(message, 500, options);
164
+ this.name = "ServerError";
165
+ Object.setPrototypeOf(this, _ServerError.prototype);
166
+ }
167
+ };
168
+
100
169
  // src/resources.ts
101
170
  var BaseResource = class {
102
171
  constructor(client) {
@@ -191,6 +260,89 @@ var MemoriesResource = class extends BaseResource {
191
260
  })
192
261
  });
193
262
  }
263
+ /**
264
+ * Create up to 100 memories with one unambiguous readiness contract.
265
+ * `wait_for_index=true` resolves only for a fully searchable batch. A durable
266
+ * server-side 202 is polled to the caller's deadline; expiry raises a typed
267
+ * `IndexingTimeoutError` carrying the original durable receipt.
268
+ */
269
+ async createBatch(params) {
270
+ if (!params.memories?.length || params.memories.length > 100) {
271
+ throw new TypeError("memories must contain between 1 and 100 items");
272
+ }
273
+ if (params.memories.some((item) => !item.content?.trim())) {
274
+ throw new TypeError("every batch memory must contain non-empty content");
275
+ }
276
+ const {
277
+ idempotency_key,
278
+ signal,
279
+ index_timeout_ms,
280
+ index_poll_interval_ms,
281
+ ...body
282
+ } = params;
283
+ const receipt = await this.client.request(
284
+ "POST",
285
+ "/v1/memories/batch",
286
+ {
287
+ headers: idempotency_key ? { "Idempotency-Key": idempotency_key } : void 0,
288
+ body: JSON.stringify({ wait_for_index: false, ...body }),
289
+ signal
290
+ }
291
+ );
292
+ if (params.wait_for_index && !receipt.searchable) {
293
+ return this.waitForBatchSearchable(receipt, {
294
+ timeoutMs: index_timeout_ms,
295
+ pollIntervalMs: index_poll_interval_ms,
296
+ signal
297
+ });
298
+ }
299
+ return receipt;
300
+ }
301
+ /** Poll every item in an asynchronous batch receipt until it is searchable. */
302
+ async waitForBatchSearchable(receipt, options = {}) {
303
+ const ids = [...new Set(receipt.memory_ids || [])];
304
+ if (!ids.length) {
305
+ throw new Error("batch receipt does not contain memory_ids");
306
+ }
307
+ const timeoutMs = Math.max(0, options.timeoutMs ?? 6e4);
308
+ const pollIntervalMs = Math.max(50, options.pollIntervalMs ?? 500);
309
+ const deadline = Date.now() + timeoutMs;
310
+ while (true) {
311
+ if (options.signal?.aborted) {
312
+ throw options.signal.reason || new Error("batch readiness polling was aborted");
313
+ }
314
+ const rows = await Promise.all(ids.map((id) => this.get(id)));
315
+ const terminal = rows.find(
316
+ (row) => ["failed", "cancelled", "canceled"].includes(
317
+ String(row.processing_status || "").toLowerCase()
318
+ )
319
+ );
320
+ if (terminal) {
321
+ throw new Error(
322
+ `memory ${terminal.id} indexing reached terminal state ${terminal.processing_status}`
323
+ );
324
+ }
325
+ if (rows.every((row) => row.searchable === true)) {
326
+ return {
327
+ ...receipt,
328
+ processing_status: "completed",
329
+ searchable: true,
330
+ results: ids.map((id) => ({
331
+ id,
332
+ memory_id: id,
333
+ processing_status: "completed"
334
+ }))
335
+ };
336
+ }
337
+ if (Date.now() >= deadline) {
338
+ throw new IndexingTimeoutError(
339
+ `batch was not searchable within ${timeoutMs}ms; the write is durable`,
340
+ receipt
341
+ );
342
+ }
343
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
344
+ }
345
+ }
194
346
  /**
195
347
  * List memories
196
348
  */
@@ -380,8 +532,7 @@ var RLResource = class extends BaseResource {
380
532
  * Train the Memory Manager agent using RL
381
533
  */
382
534
  async trainMemoryManager(params) {
383
- return this.client.post("/rl/train/memory-manager", {
384
- collection_id: params.collection_id,
535
+ return this.client.post("/v1/rl/train/memory-manager", {
385
536
  num_episodes: params.num_episodes || 100,
386
537
  ...params
387
538
  });
@@ -390,8 +541,7 @@ var RLResource = class extends BaseResource {
390
541
  * Train the Answer Agent using RL
391
542
  */
392
543
  async trainAnswerAgent(params) {
393
- return this.client.post("/rl/train/answer-agent", {
394
- collection_id: params.collection_id,
544
+ return this.client.post("/v1/rl/train/answer-agent", {
395
545
  num_episodes: params.num_episodes || 100,
396
546
  ...params
397
547
  });
@@ -400,69 +550,91 @@ var RLResource = class extends BaseResource {
400
550
  * Get RL training metrics
401
551
  */
402
552
  async getMetrics() {
403
- return this.client.get("/rl/metrics");
553
+ return this.client.get("/v1/rl/metrics");
404
554
  }
405
555
  /**
406
556
  * Evaluate a trained RL agent
407
557
  */
408
558
  async evaluate(agentType, collectionId) {
409
- return this.client.post("/rl/evaluate", {
559
+ return this.client.post("/v1/rl/evaluate", {
410
560
  agent_type: agentType,
411
561
  collection_id: collectionId
412
562
  });
413
563
  }
414
564
  };
415
565
  var ProceduralResource = class extends BaseResource {
566
+ unwrapProcedure(response) {
567
+ if (response?.procedure) return response.procedure;
568
+ if (response?.procedure_id && !response?.id) {
569
+ return { ...response, id: response.procedure_id };
570
+ }
571
+ return response;
572
+ }
416
573
  /**
417
574
  * Create a new procedure
418
575
  */
419
576
  async create(params) {
420
- return this.client.post("/procedural", {
577
+ const response = await this.client.post("/v1/procedures", {
421
578
  name: params.name,
422
579
  description: params.description,
423
- trigger_condition: params.trigger_condition,
424
- action_sequence: params.action_sequence,
580
+ condition: { expression: params.trigger_condition },
581
+ action: { steps: params.action_sequence },
425
582
  collection_id: params.collection_id,
426
583
  category: params.category,
427
- metadata: params.metadata || {}
584
+ parameters: params.metadata || {}
428
585
  });
586
+ return this.unwrapProcedure(response);
429
587
  }
430
588
  /**
431
589
  * List procedures
432
590
  */
433
591
  async list(params) {
434
- return this.client.get("/procedural", {
592
+ const response = await this.client.get("/v1/procedures", {
435
593
  collection_id: params?.collection_id,
436
594
  category: params?.category,
437
595
  skip: params?.skip || 0,
438
596
  limit: params?.limit || 100
439
597
  });
598
+ return Array.isArray(response) ? response : response?.procedures || [];
440
599
  }
441
600
  /**
442
601
  * Get a specific procedure
443
602
  */
444
603
  async get(procedureId) {
445
- return this.client.get(`/procedural/${procedureId}`);
604
+ const response = await this.client.get(`/v1/procedures/${procedureId}`);
605
+ return this.unwrapProcedure(response);
446
606
  }
447
607
  /**
448
608
  * Execute a procedure
449
609
  */
450
610
  async execute(procedureId, context) {
451
- return this.client.post(`/procedural/${procedureId}/execute`, {
452
- context: context || {}
611
+ const response = await this.client.post(`/v1/procedures/${procedureId}/execute`, {
612
+ input_state: context || {}
453
613
  });
614
+ return response?.execution_result || response;
454
615
  }
455
616
  /**
456
617
  * Update a procedure
457
618
  */
458
619
  async update(procedureId, params) {
459
- return this.client.patch(`/procedural/${procedureId}`, params);
620
+ const body = {};
621
+ if (params.name !== void 0) body.name = params.name;
622
+ if (params.description !== void 0) body.description = params.description;
623
+ if (params.trigger_condition !== void 0) {
624
+ body.condition = { expression: params.trigger_condition };
625
+ }
626
+ if (params.action_sequence !== void 0) {
627
+ body.action = { steps: params.action_sequence };
628
+ }
629
+ if (params.metadata !== void 0) body.parameters = params.metadata;
630
+ const response = await this.client.patch(`/v1/procedures/${procedureId}`, body);
631
+ return this.unwrapProcedure(response);
460
632
  }
461
633
  /**
462
634
  * Delete a procedure
463
635
  */
464
636
  async delete(procedureId) {
465
- await this.client.delete(`/procedural/${procedureId}`);
637
+ await this.client.delete(`/v1/procedures/${procedureId}`);
466
638
  }
467
639
  };
468
640
  var TemporalResource = class extends BaseResource {
@@ -470,12 +642,15 @@ var TemporalResource = class extends BaseResource {
470
642
  * Add a temporal fact to the knowledge graph
471
643
  */
472
644
  async addFact(params) {
473
- return this.client.post("/temporal/facts", {
645
+ return this.client.post("/v1/temporal/facts", {
474
646
  subject: params.subject,
647
+ subject_type: params.subject_type || "ENTITY",
475
648
  predicate: params.predicate,
476
649
  object: params.object,
650
+ object_type: params.object_type || "ENTITY",
477
651
  valid_from: params.valid_from,
478
652
  valid_until: params.valid_until,
653
+ observed_at: params.observed_at,
479
654
  confidence: params.confidence || 1,
480
655
  source_memory_id: params.source_memory_id,
481
656
  metadata: params.metadata || {}
@@ -485,29 +660,79 @@ var TemporalResource = class extends BaseResource {
485
660
  * Query temporal facts
486
661
  */
487
662
  async queryFacts(params) {
488
- return this.client.get("/temporal/facts", {
489
- subject: params?.subject,
490
- predicate: params?.predicate,
491
- object: params?.object,
492
- at_time: params?.at_time
663
+ if (!params.subject) {
664
+ throw new TypeError("subject is required by the temporal query contract");
665
+ }
666
+ let rows;
667
+ if (params.at_time) {
668
+ const response = await this.queryAtTime({
669
+ subject: params.subject,
670
+ predicate: params.predicate,
671
+ timestamp: params.at_time
672
+ });
673
+ rows = response.facts || [];
674
+ } else if (params.predicate) {
675
+ const response = await this.history(
676
+ params.subject,
677
+ params.predicate
678
+ );
679
+ rows = response.history || [];
680
+ } else {
681
+ throw new TypeError("predicate or at_time is required");
682
+ }
683
+ return params.object === void 0 ? rows : rows.filter((row) => row.object === params.object);
684
+ }
685
+ async queryAtTime(params) {
686
+ return this.client.post("/v1/temporal/facts/query-at-time", params);
687
+ }
688
+ async history(subject, predicate, limit = 50) {
689
+ return this.client.get("/v1/temporal/facts/history", {
690
+ subject,
691
+ predicate,
692
+ limit
693
+ });
694
+ }
695
+ async conflicts(subject, predicate) {
696
+ return this.client.get("/v1/temporal/facts/conflicts", {
697
+ subject,
698
+ predicate
699
+ });
700
+ }
701
+ async invalidate(subject, predicate, object) {
702
+ return this.client.post("/v1/temporal/facts/invalidate", {
703
+ subject,
704
+ predicate,
705
+ object
493
706
  });
494
707
  }
495
708
  /**
496
709
  * Query knowledge state at a specific point in time
497
710
  */
498
711
  async pointInTime(timestamp, entity) {
499
- return this.client.post("/temporal/point-in-time", {
712
+ if (!entity) {
713
+ throw new TypeError("entity is required and maps to the canonical subject");
714
+ }
715
+ return this.queryAtTime({
500
716
  timestamp,
501
- entity
717
+ subject: entity
502
718
  });
503
719
  }
720
+ /** Permanently delete a tenant-scoped temporal fact by stable ID. */
721
+ async deleteFact(factId) {
722
+ return this.client.delete(`/v1/temporal/facts/${factId}`);
723
+ }
504
724
  };
505
725
  var WorkingMemoryResource = class extends BaseResource {
726
+ constructor(client) {
727
+ super(client);
728
+ this.sessionId = `sdk-${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
729
+ }
506
730
  /**
507
731
  * Add item to working memory buffer
508
732
  */
509
733
  async add(params) {
510
- return this.client.post("/working-memory", {
734
+ return this.client.post("/v1/working-memory/add", {
735
+ session_id: params.session_id || this.sessionId,
511
736
  role: params.role,
512
737
  content: params.content,
513
738
  metadata: params.metadata || {}
@@ -516,48 +741,40 @@ var WorkingMemoryResource = class extends BaseResource {
516
741
  /**
517
742
  * Get current working memory context
518
743
  */
519
- async getContext() {
520
- return this.client.get("/working-memory/context");
744
+ async getContext(sessionId = this.sessionId, includeCompressed = false) {
745
+ return this.client.get(`/v1/working-memory/context/${sessionId}`, {
746
+ include_compressed: includeCompressed
747
+ });
521
748
  }
522
749
  /**
523
750
  * Compress working memory buffer
524
751
  */
525
- async compress() {
526
- return this.client.post("/working-memory/compress");
752
+ async compress(sessionId = this.sessionId) {
753
+ return this.client.post(`/v1/working-memory/compress/${sessionId}`);
527
754
  }
528
755
  /**
529
756
  * Clear working memory buffer
530
757
  */
531
- async clear() {
532
- return this.client.delete("/working-memory");
758
+ async clear(sessionId = this.sessionId) {
759
+ return this.client.delete(`/v1/working-memory/clear/${sessionId}`);
533
760
  }
534
761
  };
535
762
  var ConsolidationResource = class extends BaseResource {
536
763
  /**
537
764
  * Trigger memory consolidation
538
765
  */
539
- async consolidate(collectionId, threshold = 100) {
540
- return this.client.post("/consolidation/consolidate", {
766
+ async consolidate(collectionId, lookbackDays = 7, utilityThreshold = 0.3) {
767
+ return this.client.post("/v1/consolidation/consolidate", {
541
768
  collection_id: collectionId,
542
- threshold
769
+ lookback_days: lookbackDays,
770
+ utility_threshold: utilityThreshold
543
771
  });
544
772
  }
545
773
  /**
546
774
  * Get consolidation statistics
547
775
  */
548
776
  async getStats(collectionId) {
549
- return this.client.get("/consolidation/stats", {
550
- collection_id: collectionId
551
- });
552
- }
553
- /**
554
- * Archive old memories
555
- */
556
- async archive(collectionId, beforeDate) {
557
- return this.client.post("/consolidation/archive", {
558
- collection_id: collectionId,
559
- before_date: beforeDate
560
- });
777
+ return this.client.get(`/v1/consolidation/stats/${collectionId}`);
561
778
  }
562
779
  };
563
780
  var MemoryToolsResource = class extends BaseResource {
@@ -565,100 +782,38 @@ var MemoryToolsResource = class extends BaseResource {
565
782
  * Replace memory content
566
783
  */
567
784
  async replace(params) {
568
- return this.client.post("/memory-tools/replace", {
785
+ return this.client.post("/v1/memory-tools/replace", {
569
786
  memory_id: params.memory_id,
787
+ old_content: params.old_content,
570
788
  new_content: params.new_content,
571
- reason: params.reason
789
+ collection_id: params.collection_id
572
790
  });
573
791
  }
574
792
  /**
575
793
  * Insert new memory at position
576
794
  */
577
795
  async insert(params) {
578
- return this.client.post("/memory-tools/insert", {
796
+ const metadata = { ...params.metadata || {} };
797
+ if (params.position !== void 0) metadata.requested_position = params.position;
798
+ if (params.reason !== void 0) metadata.reason = params.reason;
799
+ return this.client.post("/v1/memory-tools/insert", {
579
800
  collection_id: params.collection_id,
580
801
  content: params.content,
581
- position: params.position,
582
- reason: params.reason
802
+ importance: params.importance ?? 0.5,
803
+ metadata
583
804
  });
584
805
  }
585
806
  /**
586
807
  * Re-evaluate memory in light of new information
587
808
  */
588
- async rethink(memoryId, query) {
589
- return this.client.post("/memory-tools/rethink", {
809
+ async rethink(memoryId, collectionId) {
810
+ return this.client.post("/v1/memory-tools/rethink", {
590
811
  memory_id: memoryId,
591
- query
592
- });
593
- }
594
- };
595
- var WorldModelResource = class extends BaseResource {
596
- /**
597
- * Simulate retrieval without actually retrieving
598
- */
599
- async imagineRetrieval(query, collectionId) {
600
- return this.client.post("/world-model/imagine-retrieval", {
601
- query,
602
- collection_id: collectionId
603
- });
604
- }
605
- /**
606
- * Plan memory operations to achieve goal
607
- */
608
- async plan(goal, collectionId) {
609
- return this.client.post("/world-model/plan", {
610
- goal,
611
812
  collection_id: collectionId
612
813
  });
613
814
  }
614
815
  };
615
816
 
616
- // src/errors.ts
617
- var HebbrixError = class _HebbrixError extends Error {
618
- constructor(message, statusCode) {
619
- super(message);
620
- this.name = "HebbrixError";
621
- this.statusCode = statusCode;
622
- Object.setPrototypeOf(this, _HebbrixError.prototype);
623
- }
624
- };
625
- var AuthenticationError = class _AuthenticationError extends HebbrixError {
626
- constructor(message = "Authentication failed") {
627
- super(message, 401);
628
- this.name = "AuthenticationError";
629
- Object.setPrototypeOf(this, _AuthenticationError.prototype);
630
- }
631
- };
632
- var ValidationError = class _ValidationError extends HebbrixError {
633
- constructor(message, errors) {
634
- super(message, 422);
635
- this.name = "ValidationError";
636
- this.errors = errors;
637
- Object.setPrototypeOf(this, _ValidationError.prototype);
638
- }
639
- };
640
- var NotFoundError = class _NotFoundError extends HebbrixError {
641
- constructor(message = "Resource not found") {
642
- super(message, 404);
643
- this.name = "NotFoundError";
644
- Object.setPrototypeOf(this, _NotFoundError.prototype);
645
- }
646
- };
647
- var RateLimitError = class _RateLimitError extends HebbrixError {
648
- constructor(message = "Rate limit exceeded") {
649
- super(message, 429);
650
- this.name = "RateLimitError";
651
- Object.setPrototypeOf(this, _RateLimitError.prototype);
652
- }
653
- };
654
- var ServerError = class _ServerError extends HebbrixError {
655
- constructor(message = "Internal server error") {
656
- super(message, 500);
657
- this.name = "ServerError";
658
- Object.setPrototypeOf(this, _ServerError.prototype);
659
- }
660
- };
661
-
662
817
  // src/client.ts
663
818
  var MemoryClient = class {
664
819
  constructor(config = {}) {
@@ -678,13 +833,12 @@ var MemoryClient = class {
678
833
  this.workingMemory = new WorkingMemoryResource(this);
679
834
  this.consolidation = new ConsolidationResource(this);
680
835
  this.memoryTools = new MemoryToolsResource(this);
681
- this.worldModel = new WorldModelResource(this);
682
836
  this.proofloop = new ProofLoopResource(this);
683
837
  }
684
838
  getHeaders() {
685
839
  const headers = {
686
840
  "Content-Type": "application/json",
687
- "User-Agent": "hebbrix-typescript/2.2.0"
841
+ "User-Agent": "hebbrix-typescript/2.3.0"
688
842
  };
689
843
  if (this.apiKey) {
690
844
  headers["Authorization"] = `Bearer ${this.apiKey}`;
@@ -693,39 +847,58 @@ var MemoryClient = class {
693
847
  }
694
848
  handleError(response, data) {
695
849
  const statusCode = response.status;
696
- const message = data?.error?.message || data?.detail || response.statusText;
850
+ const envelope = data?.error || data?.detail || {};
851
+ const nested = envelope?.message;
852
+ const details = nested && typeof nested === "object" ? nested : envelope;
853
+ const message = details?.message || (typeof nested === "string" ? nested : void 0) || response.statusText;
854
+ const code = details?.code || envelope?.code;
855
+ const requestId = details?.request_id || envelope?.request_id || response.headers.get("X-Request-ID") || void 0;
697
856
  if (statusCode === 401) {
698
- throw new AuthenticationError(message);
857
+ throw new AuthenticationError(message, { code, requestId, details });
699
858
  } else if (statusCode === 404) {
700
- throw new NotFoundError(message);
859
+ throw new NotFoundError(message, { code, requestId, details });
701
860
  } else if (statusCode === 422) {
702
861
  const errors = data?.error?.details || [];
703
- throw new ValidationError(message, errors);
862
+ throw new ValidationError(message, errors, { code, requestId, details });
704
863
  } else if (statusCode === 429) {
705
- throw new RateLimitError(message);
864
+ throw new RateLimitError(message, { code, requestId, details });
706
865
  } else if (statusCode >= 500) {
707
- throw new ServerError(message);
866
+ throw new ServerError(message, { code, requestId, details });
867
+ } else if ((statusCode === 402 || statusCode === 403) && (String(code || "").includes("ENTITLEMENT") || ["feature_not_available", "tier_upgrade_required"].includes(details?.error))) {
868
+ throw new EntitlementError(message, statusCode, {
869
+ code,
870
+ requestId,
871
+ details
872
+ });
708
873
  } else {
709
- throw new HebbrixError(message, statusCode);
874
+ throw new HebbrixError(message, statusCode, { code, requestId, details });
710
875
  }
711
876
  }
712
877
  async request(method, path, options = {}) {
713
878
  const url = `${this.baseUrl}${path}`;
879
+ const { headers: requestHeaders, signal: requestSignal, ...requestOptions } = options;
714
880
  const response = await fetch(url, {
881
+ ...requestOptions,
715
882
  method,
716
883
  headers: {
717
884
  ...this.getHeaders(),
718
- ...options.headers || {}
885
+ ...requestHeaders || {}
719
886
  },
720
- ...options,
721
- signal: AbortSignal.timeout(this.timeout)
887
+ signal: requestSignal || AbortSignal.timeout(this.timeout)
722
888
  });
723
- let data;
889
+ let data = void 0;
724
890
  const contentType = response.headers.get("content-type");
725
- if (contentType?.includes("application/json")) {
726
- data = await response.json();
727
- } else {
728
- data = await response.text();
891
+ const responseText = await response.text();
892
+ if (responseText) {
893
+ if (contentType?.includes("application/json")) {
894
+ try {
895
+ data = JSON.parse(responseText);
896
+ } catch {
897
+ data = { detail: responseText };
898
+ }
899
+ } else {
900
+ data = responseText;
901
+ }
729
902
  }
730
903
  if (!response.ok) {
731
904
  this.handleError(response, data);
@@ -780,7 +953,9 @@ var MemoryClient = class {
780
953
  CollectionsResource,
781
954
  ConsolidationResource,
782
955
  CorrectionsResource,
956
+ EntitlementError,
783
957
  HebbrixError,
958
+ IndexingTimeoutError,
784
959
  MemoriesResource,
785
960
  MemoryClient,
786
961
  MemoryJobsResource,
@@ -795,6 +970,5 @@ var MemoryClient = class {
795
970
  TemporalResource,
796
971
  ValidationError,
797
972
  WorkingMemoryResource,
798
- WorldModelResource,
799
973
  enforceSearchSafety
800
974
  });