@slashml/memory 1.0.10 → 1.0.11

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,189 +23,6 @@ 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
- }
209
26
 
210
27
  export interface MemoryFilters {
211
28
  user_id?: string | null;
@@ -224,12 +41,6 @@ export interface AddMemoryOptions extends MemoryFilters {
224
41
  infer?: boolean;
225
42
  memory_id?: string;
226
43
  memoryId?: string;
227
- record_tier?: string;
228
- recordTier?: string;
229
- slot_key?: string;
230
- slotKey?: string;
231
- scope?: RuleScope | RuleScopePattern;
232
- contrastive?: ContrastiveRuleTriplet;
233
44
  }
234
45
 
235
46
  export interface SearchMemoryOptions extends MemoryFilters {
@@ -237,30 +48,18 @@ export interface SearchMemoryOptions extends MemoryFilters {
237
48
  top_k?: number;
238
49
  topK?: number;
239
50
  threshold?: number;
240
- record_tier?: string;
241
- recordTier?: string;
242
51
  }
243
52
 
244
53
  export interface IngestOptions {
245
54
  namespace?: string;
246
55
  model?: string;
247
56
  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;
254
57
  }
255
58
 
256
59
  export interface QueryOptions {
257
60
  namespace?: string;
258
61
  model?: string;
259
62
  top_k?: number;
260
- record_tier?: string;
261
- recordTier?: string;
262
- context?: Record<string, unknown>;
263
- include_rules?: boolean;
264
63
  }
265
64
 
266
65
  export interface ForgetOptions {
@@ -327,9 +126,9 @@ export class SlashMLAPIError extends Error {
327
126
  }
328
127
 
329
128
  function getEnv(name: string): string | undefined {
330
- const proc = (globalThis as any).process;
331
- if (typeof proc !== "undefined" && proc && proc.env) {
332
- return proc.env[name];
129
+ const g = globalThis as unknown as { process?: { env?: Record<string, string | undefined> } };
130
+ if (typeof g.process !== "undefined" && g.process.env) {
131
+ return g.process.env[name];
333
132
  }
334
133
  return undefined;
335
134
  }
@@ -531,7 +330,7 @@ export class MemoryClient {
531
330
  const headers: Record<string, string> = {
532
331
  Accept: "application/json",
533
332
  "Content-Type": "application/json",
534
- "User-Agent": "slashml-memory-ts/1.0.10",
333
+ "User-Agent": "slashml-memory-ts/1.0.11",
535
334
  };
536
335
  if (this.apiKey) {
537
336
  headers.Authorization = `Bearer ${this.apiKey}`;
@@ -596,32 +395,12 @@ export class MemoryClient {
596
395
  options: IngestOptions = {},
597
396
  ): Promise<Record<string, unknown>> {
598
397
  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
- }
617
398
  return this.request("POST", "/v1/memory/ingest", {
618
399
  jsonBody: {
619
400
  namespace: options.namespace ?? "default",
620
401
  model: options.model ?? this.model,
621
402
  documents: docs,
622
- metadata: meta,
623
- ...(meta.record_tier ? { record_tier: meta.record_tier } : {}),
624
- ...(meta.slot_key ? { slot_key: meta.slot_key } : {}),
403
+ metadata: options.metadata ?? {},
625
404
  },
626
405
  });
627
406
  }
@@ -630,19 +409,13 @@ export class MemoryClient {
630
409
  prompt: string,
631
410
  options: QueryOptions = {},
632
411
  ): 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);
644
412
  return this.request("POST", "/v1/memory/query", {
645
- jsonBody: payload,
413
+ jsonBody: {
414
+ namespace: options.namespace ?? "default",
415
+ model: options.model ?? this.model,
416
+ prompt,
417
+ top_k: options.top_k ?? 5,
418
+ },
646
419
  });
647
420
  }
648
421
 
@@ -724,113 +497,6 @@ export class MemoryClient {
724
497
  });
725
498
  }
726
499
 
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
-
834
500
  // ---------------------------------------------------------------------------
835
501
  // Mem0-Compatible REST Endpoints (/v1/memories/*)
836
502
  // ---------------------------------------------------------------------------
@@ -846,24 +512,6 @@ export class MemoryClient {
846
512
  : Array.isArray(messages)
847
513
  ? messages
848
514
  : [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
- }
867
515
  const payload: Record<string, unknown> = {
868
516
  messages: normalizedMessages,
869
517
  ...(typeof messages === "string" ? { text: messages } : {}),
@@ -871,9 +519,7 @@ export class MemoryClient {
871
519
  agent_id: options.agent_id ?? options.agentId ?? null,
872
520
  app_id: options.app_id ?? options.appId ?? null,
873
521
  run_id: options.run_id ?? options.runId ?? null,
874
- metadata: meta,
875
- ...(meta.record_tier ? { record_tier: meta.record_tier } : {}),
876
- ...(meta.slot_key ? { slot_key: meta.slot_key } : {}),
522
+ metadata: options.metadata ?? {},
877
523
  infer: options.infer ?? true,
878
524
  model: this.model,
879
525
  };