@slashml/memory 1.0.8 → 1.0.9

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/src/index.ts CHANGED
@@ -23,6 +23,189 @@ export interface MemoryClientOptions {
23
23
  timeoutMs?: number;
24
24
  fetchImpl?: typeof fetch;
25
25
  }
26
+
27
+ export interface RuleScopePattern {
28
+ file_paths?: string[];
29
+ tool_names?: string[];
30
+ environments?: string[];
31
+ git_branches?: string[];
32
+ }
33
+
34
+ export class RuleScope {
35
+ public file_paths: string[];
36
+ public tool_names: string[];
37
+ public environments: string[];
38
+ public git_branches: string[];
39
+
40
+ constructor(patterns: RuleScopePattern = {}) {
41
+ this.file_paths = patterns.file_paths ?? [];
42
+ this.tool_names = patterns.tool_names ?? [];
43
+ this.environments = patterns.environments ?? [];
44
+ this.git_branches = patterns.git_branches ?? [];
45
+ }
46
+
47
+ public matches(context?: Record<string, unknown> | null): boolean {
48
+ if (!context) return true;
49
+ const hasAnyConstraint =
50
+ this.file_paths.length > 0 ||
51
+ this.tool_names.length > 0 ||
52
+ this.environments.length > 0 ||
53
+ this.git_branches.length > 0;
54
+ if (!hasAnyConstraint) return true;
55
+
56
+ if (this.file_paths.length > 0 && context.file_path) {
57
+ const p = String(context.file_path).toLowerCase();
58
+ if (!this.file_paths.some((pattern) => p.includes(pattern.toLowerCase()))) return false;
59
+ }
60
+ if (this.tool_names.length > 0 && context.tool_name) {
61
+ const t = String(context.tool_name).toLowerCase();
62
+ if (!this.tool_names.some((tn) => tn.toLowerCase() === t)) return false;
63
+ }
64
+ if (this.environments.length > 0 && context.environment) {
65
+ const e = String(context.environment).toLowerCase();
66
+ if (!this.environments.some((env) => env.toLowerCase() === e)) return false;
67
+ }
68
+ if (this.git_branches.length > 0 && context.git_branch) {
69
+ const b = String(context.git_branch).toLowerCase();
70
+ if (!this.git_branches.some((br) => br.toLowerCase() === b)) return false;
71
+ }
72
+ return true;
73
+ }
74
+
75
+ public toJSON(): Record<string, string[]> {
76
+ return {
77
+ file_paths: this.file_paths,
78
+ tool_names: this.tool_names,
79
+ environments: this.environments,
80
+ git_branches: this.git_branches,
81
+ };
82
+ }
83
+ }
84
+
85
+ export interface ContrastiveRuleTriplet {
86
+ rule_id: string;
87
+ do: string;
88
+ dont: string;
89
+ context?: string;
90
+ scope?: RuleScope | RuleScopePattern;
91
+ raw_text?: string;
92
+ }
93
+
94
+ export interface CacheAlignedPromptResult {
95
+ zone1_rules_text: string;
96
+ zone2_facts_text: string;
97
+ user_turn: string;
98
+ whisper_block: string;
99
+ full_prompt_text: string;
100
+ has_cache_breakpoint: boolean;
101
+ token_economics: Record<string, unknown>;
102
+ }
103
+
104
+ export function extractCanonicalSlotKey(
105
+ text: string,
106
+ metadata?: Record<string, unknown> | null,
107
+ ): string | null {
108
+ if (metadata && metadata.slot_key) {
109
+ return String(metadata.slot_key).trim().toLowerCase();
110
+ }
111
+ return null;
112
+ }
113
+
114
+ export function compileContrastiveRule(
115
+ text: string,
116
+ ruleId?: string,
117
+ scope?: RuleScope | RuleScopePattern,
118
+ options?: { do?: string; dont?: string },
119
+ ): ContrastiveRuleTriplet {
120
+ const cleanText = text.trim();
121
+ const rid = ruleId || `rule_${Math.floor(Math.random() * 900000 + 100000)}`;
122
+ const parsedScope = scope instanceof RuleScope ? scope : new RuleScope(scope);
123
+
124
+ return {
125
+ rule_id: rid,
126
+ do: options?.do || cleanText,
127
+ dont: options?.dont || "",
128
+ scope: parsedScope,
129
+ raw_text: cleanText,
130
+ };
131
+ }
132
+
133
+ export function formatCacheAlignedPrompt(
134
+ rules: ContrastiveRuleTriplet[],
135
+ facts: Array<string | { text?: string; memory?: string }>,
136
+ userPrompt: string,
137
+ options: {
138
+ activeContext?: Record<string, unknown>;
139
+ whisperRule?: ContrastiveRuleTriplet | null;
140
+ enableCacheBreakpoint?: boolean;
141
+ } = {},
142
+ ): CacheAlignedPromptResult {
143
+ const activeContext = options.activeContext;
144
+ const enableCacheBreakpoint = options.enableCacheBreakpoint ?? true;
145
+
146
+ const activeRules = rules.filter((r) => {
147
+ if (!r.scope) return true;
148
+ const scopeObj = r.scope instanceof RuleScope ? r.scope : new RuleScope(r.scope);
149
+ return scopeObj.matches(activeContext);
150
+ });
151
+
152
+ const zone1Lines: string[] = [];
153
+ if (activeRules.length > 0) {
154
+ zone1Lines.push("<rules>");
155
+ for (const r of activeRules) {
156
+ zone1Lines.push(` <rule id="${r.rule_id}">\n <do>${r.do}</do>\n <dont>${r.dont}</dont>\n </rule>`);
157
+ }
158
+ zone1Lines.push("</rules>");
159
+ }
160
+ const zone1Text = zone1Lines.join("\n");
161
+
162
+ const zone2Lines: string[] = [];
163
+ if (facts.length > 0) {
164
+ zone2Lines.push("<facts>");
165
+ for (const f of facts) {
166
+ const fText = typeof f === "string" ? f : f?.text ?? f?.memory ?? "";
167
+ if (fText) {
168
+ zone2Lines.push(` <fact>${fText}</fact>`);
169
+ }
170
+ }
171
+ zone2Lines.push("</facts>");
172
+ }
173
+ const zone2Text = zone2Lines.join("\n");
174
+
175
+ let whisperText = "";
176
+ if (options.whisperRule) {
177
+ whisperText = `<whisper>\n [CRITICAL CONSTRAINT ACTIVE]\n DO: ${options.whisperRule.do}\n DON'T: ${options.whisperRule.dont}\n</whisper>`;
178
+ }
179
+
180
+ const parts: string[] = [];
181
+ if (zone1Text) parts.push(zone1Text);
182
+ if (enableCacheBreakpoint && zone1Text) parts.push("<!-- cache_control: ephemeral_breakpoint -->");
183
+ if (zone2Text) parts.push(zone2Text);
184
+ if (whisperText) parts.push(whisperText);
185
+ parts.push(userPrompt);
186
+
187
+ const fullPrompt = parts.filter(Boolean).join("\n\n");
188
+ const z1Tok = zone1Text ? Math.max(1, Math.floor(zone1Text.length / 4)) : 0;
189
+ const z2Tok = zone2Text ? Math.max(1, Math.floor(zone2Text.length / 4)) : 0;
190
+ const uTok = Math.max(1, Math.floor(userPrompt.length / 4));
191
+ const totTok = z1Tok + z2Tok + uTok;
192
+
193
+ return {
194
+ zone1_rules_text: zone1Text,
195
+ zone2_facts_text: zone2Text,
196
+ user_turn: userPrompt,
197
+ whisper_block: whisperText,
198
+ full_prompt_text: fullPrompt,
199
+ has_cache_breakpoint: enableCacheBreakpoint && Boolean(zone1Text),
200
+ token_economics: {
201
+ zone1_tokens_estimated: z1Tok,
202
+ zone2_tokens_estimated: z2Tok,
203
+ user_tokens_estimated: uTok,
204
+ total_tokens_estimated: totTok,
205
+ prefix_cache_eligible_ratio: totTok > 0 ? Number((z1Tok / totTok).toFixed(3)) : 0.0,
206
+ },
207
+ };
208
+ }
26
209
 
27
210
  export interface MemoryFilters {
28
211
  user_id?: string | null;
@@ -41,6 +224,12 @@ export interface AddMemoryOptions extends MemoryFilters {
41
224
  infer?: boolean;
42
225
  memory_id?: string;
43
226
  memoryId?: string;
227
+ record_tier?: string;
228
+ recordTier?: string;
229
+ slot_key?: string;
230
+ slotKey?: string;
231
+ scope?: RuleScope | RuleScopePattern;
232
+ contrastive?: ContrastiveRuleTriplet;
44
233
  }
45
234
 
46
235
  export interface SearchMemoryOptions extends MemoryFilters {
@@ -48,18 +237,30 @@ export interface SearchMemoryOptions extends MemoryFilters {
48
237
  top_k?: number;
49
238
  topK?: number;
50
239
  threshold?: number;
240
+ record_tier?: string;
241
+ recordTier?: string;
51
242
  }
52
243
 
53
244
  export interface IngestOptions {
54
245
  namespace?: string;
55
246
  model?: string;
56
247
  metadata?: Record<string, unknown>;
248
+ record_tier?: string;
249
+ recordTier?: string;
250
+ slot_key?: string;
251
+ slotKey?: string;
252
+ scope?: RuleScope | RuleScopePattern;
253
+ contrastive?: ContrastiveRuleTriplet;
57
254
  }
58
255
 
59
256
  export interface QueryOptions {
60
257
  namespace?: string;
61
258
  model?: string;
62
259
  top_k?: number;
260
+ record_tier?: string;
261
+ recordTier?: string;
262
+ context?: Record<string, unknown>;
263
+ include_rules?: boolean;
63
264
  }
64
265
 
65
266
  export interface ForgetOptions {
@@ -126,8 +327,9 @@ export class SlashMLAPIError extends Error {
126
327
  }
127
328
 
128
329
  function getEnv(name: string): string | undefined {
129
- if (typeof process !== "undefined" && process.env) {
130
- return process.env[name];
330
+ const proc = (globalThis as any).process;
331
+ if (typeof proc !== "undefined" && proc && proc.env) {
332
+ return proc.env[name];
131
333
  }
132
334
  return undefined;
133
335
  }
@@ -329,7 +531,7 @@ export class MemoryClient {
329
531
  const headers: Record<string, string> = {
330
532
  Accept: "application/json",
331
533
  "Content-Type": "application/json",
332
- "User-Agent": "slashml-memory-ts/1.0.8",
534
+ "User-Agent": "slashml-memory-ts/1.0.9",
333
535
  };
334
536
  if (this.apiKey) {
335
537
  headers.Authorization = `Bearer ${this.apiKey}`;
@@ -394,12 +596,32 @@ export class MemoryClient {
394
596
  options: IngestOptions = {},
395
597
  ): Promise<Record<string, unknown>> {
396
598
  const docs = typeof documents === "string" ? [documents] : Array.from(documents);
599
+ const meta: Record<string, unknown> = { ...(options.metadata ?? {}) };
600
+ const effectiveTier = options.record_tier ?? options.recordTier ?? meta.record_tier ?? meta.tier;
601
+ if (effectiveTier) meta.record_tier = String(effectiveTier);
602
+ let effectiveSlot = options.slot_key ?? options.slotKey ?? meta.slot_key;
603
+ if (!effectiveSlot && typeof documents === "string") {
604
+ effectiveSlot = extractCanonicalSlotKey(documents, meta) ?? undefined;
605
+ }
606
+ if (effectiveSlot) meta.slot_key = String(effectiveSlot);
607
+ if (options.scope) {
608
+ meta.scope = options.scope instanceof RuleScope ? options.scope.toJSON() : options.scope;
609
+ }
610
+ if (options.contrastive) {
611
+ meta.contrastive = {
612
+ do: options.contrastive.do,
613
+ dont: options.contrastive.dont,
614
+ context: options.contrastive.context,
615
+ };
616
+ }
397
617
  return this.request("POST", "/v1/memory/ingest", {
398
618
  jsonBody: {
399
619
  namespace: options.namespace ?? "default",
400
620
  model: options.model ?? this.model,
401
621
  documents: docs,
402
- metadata: options.metadata ?? {},
622
+ metadata: meta,
623
+ ...(meta.record_tier ? { record_tier: meta.record_tier } : {}),
624
+ ...(meta.slot_key ? { slot_key: meta.slot_key } : {}),
403
625
  },
404
626
  });
405
627
  }
@@ -408,13 +630,19 @@ export class MemoryClient {
408
630
  prompt: string,
409
631
  options: QueryOptions = {},
410
632
  ): Promise<Record<string, unknown>> {
633
+ const payload: Record<string, unknown> = {
634
+ namespace: options.namespace ?? "default",
635
+ model: options.model ?? this.model,
636
+ prompt,
637
+ query: prompt,
638
+ top_k: options.top_k ?? 5,
639
+ };
640
+ const effectiveTier = options.record_tier ?? options.recordTier;
641
+ if (effectiveTier) payload.record_tier = String(effectiveTier);
642
+ if (options.context) payload.context = options.context;
643
+ if (options.include_rules !== undefined) payload.include_rules = Boolean(options.include_rules);
411
644
  return this.request("POST", "/v1/memory/query", {
412
- jsonBody: {
413
- namespace: options.namespace ?? "default",
414
- model: options.model ?? this.model,
415
- prompt,
416
- top_k: options.top_k ?? 5,
417
- },
645
+ jsonBody: payload,
418
646
  });
419
647
  }
420
648
 
@@ -496,6 +724,113 @@ export class MemoryClient {
496
724
  });
497
725
  }
498
726
 
727
+ // ---------------------------------------------------------------------------
728
+ // Phase 30 Dual-Tier & Prompt-Cache Features
729
+ // ---------------------------------------------------------------------------
730
+
731
+ public async addRule(
732
+ text: string,
733
+ options: {
734
+ rule_id?: string;
735
+ ruleId?: string;
736
+ do?: string;
737
+ dont?: string;
738
+ scope?: RuleScope | RuleScopePattern;
739
+ user_id?: string;
740
+ userId?: string;
741
+ metadata?: Record<string, unknown>;
742
+ } = {},
743
+ ): Promise<Record<string, unknown>> {
744
+ const compiled = compileContrastiveRule(text, options.rule_id || options.ruleId, options.scope);
745
+ if (options.do) compiled.do = options.do;
746
+ if (options.dont) compiled.dont = options.dont;
747
+ const meta: Record<string, unknown> = {
748
+ ...(options.metadata ?? {}),
749
+ rule_id: compiled.rule_id,
750
+ scope: compiled.scope instanceof RuleScope ? compiled.scope.toJSON() : compiled.scope,
751
+ contrastive: { do: compiled.do, dont: compiled.dont },
752
+ record_tier: "rule",
753
+ };
754
+ return this.ingest(text, {
755
+ record_tier: "rule",
756
+ metadata: meta,
757
+ scope: compiled.scope,
758
+ contrastive: compiled,
759
+ });
760
+ }
761
+
762
+ public async add_rule(
763
+ text: string,
764
+ options: {
765
+ rule_id?: string;
766
+ ruleId?: string;
767
+ do?: string;
768
+ dont?: string;
769
+ scope?: RuleScope | RuleScopePattern;
770
+ user_id?: string;
771
+ userId?: string;
772
+ metadata?: Record<string, unknown>;
773
+ } = {},
774
+ ): Promise<Record<string, unknown>> {
775
+ return this.addRule(text, options);
776
+ }
777
+
778
+ public async getCacheAlignedPrompt(
779
+ userTurn: string,
780
+ options: {
781
+ activeContext?: Record<string, unknown>;
782
+ top_k?: number;
783
+ userId?: string;
784
+ user_id?: string;
785
+ enableCacheBreakpoint?: boolean;
786
+ } = {},
787
+ ): Promise<CacheAlignedPromptResult> {
788
+ const rulesRes = await this.query(userTurn, {
789
+ top_k: 20,
790
+ record_tier: "rule",
791
+ context: options.activeContext,
792
+ });
793
+ const rawRules = (rulesRes?.results as any[]) || (rulesRes?.memories as any[]) || [];
794
+ const rulesList: ContrastiveRuleTriplet[] = rawRules.map((r: any) => {
795
+ const rMeta = r.metadata || {};
796
+ const cInfo = rMeta.contrastive || {};
797
+ const sInfo = rMeta.scope || {};
798
+ return {
799
+ rule_id: String(r.id || rMeta.rule_id || "rule"),
800
+ do: String(cInfo.do || r.text || ""),
801
+ dont: String(cInfo.dont || ""),
802
+ context: String(cInfo.context || ""),
803
+ scope: new RuleScope(sInfo),
804
+ raw_text: String(r.text || ""),
805
+ };
806
+ });
807
+
808
+ const factsRes = await this.query(userTurn, {
809
+ top_k: options.top_k || 5,
810
+ record_tier: "fact",
811
+ });
812
+ const rawFacts = (factsRes?.results as any[]) || (factsRes?.memories as any[]) || [];
813
+ const factsList = rawFacts.map((f: any) => String(f.text || f.memory || ""));
814
+
815
+ return formatCacheAlignedPrompt(rulesList, factsList, userTurn, {
816
+ activeContext: options.activeContext,
817
+ enableCacheBreakpoint: options.enableCacheBreakpoint ?? true,
818
+ });
819
+ }
820
+
821
+ public async get_cache_aligned_prompt(
822
+ userTurn: string,
823
+ options: {
824
+ activeContext?: Record<string, unknown>;
825
+ top_k?: number;
826
+ userId?: string;
827
+ user_id?: string;
828
+ enableCacheBreakpoint?: boolean;
829
+ } = {},
830
+ ): Promise<CacheAlignedPromptResult> {
831
+ return this.getCacheAlignedPrompt(userTurn, options);
832
+ }
833
+
499
834
  // ---------------------------------------------------------------------------
500
835
  // Mem0-Compatible REST Endpoints (/v1/memories/*)
501
836
  // ---------------------------------------------------------------------------
@@ -511,6 +846,24 @@ export class MemoryClient {
511
846
  : Array.isArray(messages)
512
847
  ? messages
513
848
  : [messages];
849
+ const meta: Record<string, unknown> = { ...(options.metadata ?? {}) };
850
+ const effectiveTier = options.record_tier ?? options.recordTier ?? meta.record_tier ?? meta.tier;
851
+ if (effectiveTier) meta.record_tier = String(effectiveTier);
852
+ let effectiveSlot = options.slot_key ?? options.slotKey ?? meta.slot_key;
853
+ if (!effectiveSlot && typeof messages === "string") {
854
+ effectiveSlot = extractCanonicalSlotKey(messages, meta) ?? undefined;
855
+ }
856
+ if (effectiveSlot) meta.slot_key = String(effectiveSlot);
857
+ if (options.scope) {
858
+ meta.scope = options.scope instanceof RuleScope ? options.scope.toJSON() : options.scope;
859
+ }
860
+ if (options.contrastive) {
861
+ meta.contrastive = {
862
+ do: options.contrastive.do,
863
+ dont: options.contrastive.dont,
864
+ context: options.contrastive.context,
865
+ };
866
+ }
514
867
  const payload: Record<string, unknown> = {
515
868
  messages: normalizedMessages,
516
869
  ...(typeof messages === "string" ? { text: messages } : {}),
@@ -518,7 +871,9 @@ export class MemoryClient {
518
871
  agent_id: options.agent_id ?? options.agentId ?? null,
519
872
  app_id: options.app_id ?? options.appId ?? null,
520
873
  run_id: options.run_id ?? options.runId ?? null,
521
- metadata: options.metadata ?? {},
874
+ metadata: meta,
875
+ ...(meta.record_tier ? { record_tier: meta.record_tier } : {}),
876
+ ...(meta.slot_key ? { slot_key: meta.slot_key } : {}),
522
877
  infer: options.infer ?? true,
523
878
  model: this.model,
524
879
  };