@slashml/memory 1.0.9 → 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/dist/index.d.ts CHANGED
@@ -21,51 +21,6 @@ export interface MemoryClientOptions {
21
21
  timeoutMs?: number;
22
22
  fetchImpl?: typeof fetch;
23
23
  }
24
- export interface RuleScopePattern {
25
- file_paths?: string[];
26
- tool_names?: string[];
27
- environments?: string[];
28
- git_branches?: string[];
29
- }
30
- export declare class RuleScope {
31
- file_paths: string[];
32
- tool_names: string[];
33
- environments: string[];
34
- git_branches: string[];
35
- constructor(patterns?: RuleScopePattern);
36
- matches(context?: Record<string, unknown> | null): boolean;
37
- toJSON(): Record<string, string[]>;
38
- }
39
- export interface ContrastiveRuleTriplet {
40
- rule_id: string;
41
- do: string;
42
- dont: string;
43
- context?: string;
44
- scope?: RuleScope | RuleScopePattern;
45
- raw_text?: string;
46
- }
47
- export interface CacheAlignedPromptResult {
48
- zone1_rules_text: string;
49
- zone2_facts_text: string;
50
- user_turn: string;
51
- whisper_block: string;
52
- full_prompt_text: string;
53
- has_cache_breakpoint: boolean;
54
- token_economics: Record<string, unknown>;
55
- }
56
- export declare function extractCanonicalSlotKey(text: string, metadata?: Record<string, unknown> | null): string | null;
57
- export declare function compileContrastiveRule(text: string, ruleId?: string, scope?: RuleScope | RuleScopePattern, options?: {
58
- do?: string;
59
- dont?: string;
60
- }): ContrastiveRuleTriplet;
61
- export declare function formatCacheAlignedPrompt(rules: ContrastiveRuleTriplet[], facts: Array<string | {
62
- text?: string;
63
- memory?: string;
64
- }>, userPrompt: string, options?: {
65
- activeContext?: Record<string, unknown>;
66
- whisperRule?: ContrastiveRuleTriplet | null;
67
- enableCacheBreakpoint?: boolean;
68
- }): CacheAlignedPromptResult;
69
24
  export interface MemoryFilters {
70
25
  user_id?: string | null;
71
26
  userId?: string | null;
@@ -82,40 +37,22 @@ export interface AddMemoryOptions extends MemoryFilters {
82
37
  infer?: boolean;
83
38
  memory_id?: string;
84
39
  memoryId?: string;
85
- record_tier?: string;
86
- recordTier?: string;
87
- slot_key?: string;
88
- slotKey?: string;
89
- scope?: RuleScope | RuleScopePattern;
90
- contrastive?: ContrastiveRuleTriplet;
91
40
  }
92
41
  export interface SearchMemoryOptions extends MemoryFilters {
93
42
  limit?: number;
94
43
  top_k?: number;
95
44
  topK?: number;
96
45
  threshold?: number;
97
- record_tier?: string;
98
- recordTier?: string;
99
46
  }
100
47
  export interface IngestOptions {
101
48
  namespace?: string;
102
49
  model?: string;
103
50
  metadata?: Record<string, unknown>;
104
- record_tier?: string;
105
- recordTier?: string;
106
- slot_key?: string;
107
- slotKey?: string;
108
- scope?: RuleScope | RuleScopePattern;
109
- contrastive?: ContrastiveRuleTriplet;
110
51
  }
111
52
  export interface QueryOptions {
112
53
  namespace?: string;
113
54
  model?: string;
114
55
  top_k?: number;
115
- record_tier?: string;
116
- recordTier?: string;
117
- context?: Record<string, unknown>;
118
- include_rules?: boolean;
119
56
  }
120
57
  export interface ForgetOptions {
121
58
  namespace?: string;
@@ -219,40 +156,6 @@ export declare class MemoryClient {
219
156
  forget(target: string, options?: ForgetOptions): Promise<Record<string, unknown>>;
220
157
  intervene(textOrPayload: string | InterveneOptions, options?: InterveneOptions): Promise<Record<string, unknown>>;
221
158
  status(options?: StatusOptions): Promise<Record<string, unknown>>;
222
- addRule(text: string, options?: {
223
- rule_id?: string;
224
- ruleId?: string;
225
- do?: string;
226
- dont?: string;
227
- scope?: RuleScope | RuleScopePattern;
228
- user_id?: string;
229
- userId?: string;
230
- metadata?: Record<string, unknown>;
231
- }): Promise<Record<string, unknown>>;
232
- add_rule(text: string, options?: {
233
- rule_id?: string;
234
- ruleId?: string;
235
- do?: string;
236
- dont?: string;
237
- scope?: RuleScope | RuleScopePattern;
238
- user_id?: string;
239
- userId?: string;
240
- metadata?: Record<string, unknown>;
241
- }): Promise<Record<string, unknown>>;
242
- getCacheAlignedPrompt(userTurn: string, options?: {
243
- activeContext?: Record<string, unknown>;
244
- top_k?: number;
245
- userId?: string;
246
- user_id?: string;
247
- enableCacheBreakpoint?: boolean;
248
- }): Promise<CacheAlignedPromptResult>;
249
- get_cache_aligned_prompt(userTurn: string, options?: {
250
- activeContext?: Record<string, unknown>;
251
- top_k?: number;
252
- userId?: string;
253
- user_id?: string;
254
- enableCacheBreakpoint?: boolean;
255
- }): Promise<CacheAlignedPromptResult>;
256
159
  add(messages: string | Array<Record<string, unknown>> | Record<string, unknown>, options?: AddMemoryOptions): Promise<Record<string, unknown>>;
257
160
  search(queryOrOptions: string | ({
258
161
  query: string;
package/dist/index.js CHANGED
@@ -5,148 +5,10 @@
5
5
  * 100% drop-in replacement for `mem0ai` (`MemoryClient`, `AsyncMemoryClient`, `Memory`, `AsyncMemory`).
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.AsyncSlashMLClient = exports.AsyncSlashMLMemory = exports.SlashMLClient = exports.SlashMLMemory = exports.AsyncMemory = exports.AsyncMemoryClient = exports.Memory = exports.MemoryClient = exports.ProjectManager = exports.SlashMLAPIError = exports.RuleScope = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_MODEL = exports.DEFAULT_BASE_URL = void 0;
9
- exports.extractCanonicalSlotKey = extractCanonicalSlotKey;
10
- exports.compileContrastiveRule = compileContrastiveRule;
11
- exports.formatCacheAlignedPrompt = formatCacheAlignedPrompt;
8
+ exports.AsyncSlashMLClient = exports.AsyncSlashMLMemory = exports.SlashMLClient = exports.SlashMLMemory = exports.AsyncMemory = exports.AsyncMemoryClient = exports.Memory = exports.MemoryClient = exports.ProjectManager = exports.SlashMLAPIError = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_MODEL = exports.DEFAULT_BASE_URL = void 0;
12
9
  exports.DEFAULT_BASE_URL = "https://api.slashml.ai";
13
10
  exports.DEFAULT_MODEL = "slashml-1.5-fast";
14
11
  exports.DEFAULT_TIMEOUT_MS = 30_000;
15
- class RuleScope {
16
- file_paths;
17
- tool_names;
18
- environments;
19
- git_branches;
20
- constructor(patterns = {}) {
21
- this.file_paths = patterns.file_paths ?? [];
22
- this.tool_names = patterns.tool_names ?? [];
23
- this.environments = patterns.environments ?? [];
24
- this.git_branches = patterns.git_branches ?? [];
25
- }
26
- matches(context) {
27
- if (!context)
28
- return true;
29
- const hasAnyConstraint = this.file_paths.length > 0 ||
30
- this.tool_names.length > 0 ||
31
- this.environments.length > 0 ||
32
- this.git_branches.length > 0;
33
- if (!hasAnyConstraint)
34
- return true;
35
- if (this.file_paths.length > 0 && context.file_path) {
36
- const p = String(context.file_path).toLowerCase();
37
- if (!this.file_paths.some((pattern) => p.includes(pattern.toLowerCase())))
38
- return false;
39
- }
40
- if (this.tool_names.length > 0 && context.tool_name) {
41
- const t = String(context.tool_name).toLowerCase();
42
- if (!this.tool_names.some((tn) => tn.toLowerCase() === t))
43
- return false;
44
- }
45
- if (this.environments.length > 0 && context.environment) {
46
- const e = String(context.environment).toLowerCase();
47
- if (!this.environments.some((env) => env.toLowerCase() === e))
48
- return false;
49
- }
50
- if (this.git_branches.length > 0 && context.git_branch) {
51
- const b = String(context.git_branch).toLowerCase();
52
- if (!this.git_branches.some((br) => br.toLowerCase() === b))
53
- return false;
54
- }
55
- return true;
56
- }
57
- toJSON() {
58
- return {
59
- file_paths: this.file_paths,
60
- tool_names: this.tool_names,
61
- environments: this.environments,
62
- git_branches: this.git_branches,
63
- };
64
- }
65
- }
66
- exports.RuleScope = RuleScope;
67
- function extractCanonicalSlotKey(text, metadata) {
68
- if (metadata && metadata.slot_key) {
69
- return String(metadata.slot_key).trim().toLowerCase();
70
- }
71
- return null;
72
- }
73
- function compileContrastiveRule(text, ruleId, scope, options) {
74
- const cleanText = text.trim();
75
- const rid = ruleId || `rule_${Math.floor(Math.random() * 900000 + 100000)}`;
76
- const parsedScope = scope instanceof RuleScope ? scope : new RuleScope(scope);
77
- return {
78
- rule_id: rid,
79
- do: options?.do || cleanText,
80
- dont: options?.dont || "",
81
- scope: parsedScope,
82
- raw_text: cleanText,
83
- };
84
- }
85
- function formatCacheAlignedPrompt(rules, facts, userPrompt, options = {}) {
86
- const activeContext = options.activeContext;
87
- const enableCacheBreakpoint = options.enableCacheBreakpoint ?? true;
88
- const activeRules = rules.filter((r) => {
89
- if (!r.scope)
90
- return true;
91
- const scopeObj = r.scope instanceof RuleScope ? r.scope : new RuleScope(r.scope);
92
- return scopeObj.matches(activeContext);
93
- });
94
- const zone1Lines = [];
95
- if (activeRules.length > 0) {
96
- zone1Lines.push("<rules>");
97
- for (const r of activeRules) {
98
- zone1Lines.push(` <rule id="${r.rule_id}">\n <do>${r.do}</do>\n <dont>${r.dont}</dont>\n </rule>`);
99
- }
100
- zone1Lines.push("</rules>");
101
- }
102
- const zone1Text = zone1Lines.join("\n");
103
- const zone2Lines = [];
104
- if (facts.length > 0) {
105
- zone2Lines.push("<facts>");
106
- for (const f of facts) {
107
- const fText = typeof f === "string" ? f : f?.text ?? f?.memory ?? "";
108
- if (fText) {
109
- zone2Lines.push(` <fact>${fText}</fact>`);
110
- }
111
- }
112
- zone2Lines.push("</facts>");
113
- }
114
- const zone2Text = zone2Lines.join("\n");
115
- let whisperText = "";
116
- if (options.whisperRule) {
117
- whisperText = `<whisper>\n [CRITICAL CONSTRAINT ACTIVE]\n DO: ${options.whisperRule.do}\n DON'T: ${options.whisperRule.dont}\n</whisper>`;
118
- }
119
- const parts = [];
120
- if (zone1Text)
121
- parts.push(zone1Text);
122
- if (enableCacheBreakpoint && zone1Text)
123
- parts.push("<!-- cache_control: ephemeral_breakpoint -->");
124
- if (zone2Text)
125
- parts.push(zone2Text);
126
- if (whisperText)
127
- parts.push(whisperText);
128
- parts.push(userPrompt);
129
- const fullPrompt = parts.filter(Boolean).join("\n\n");
130
- const z1Tok = zone1Text ? Math.max(1, Math.floor(zone1Text.length / 4)) : 0;
131
- const z2Tok = zone2Text ? Math.max(1, Math.floor(zone2Text.length / 4)) : 0;
132
- const uTok = Math.max(1, Math.floor(userPrompt.length / 4));
133
- const totTok = z1Tok + z2Tok + uTok;
134
- return {
135
- zone1_rules_text: zone1Text,
136
- zone2_facts_text: zone2Text,
137
- user_turn: userPrompt,
138
- whisper_block: whisperText,
139
- full_prompt_text: fullPrompt,
140
- has_cache_breakpoint: enableCacheBreakpoint && Boolean(zone1Text),
141
- token_economics: {
142
- zone1_tokens_estimated: z1Tok,
143
- zone2_tokens_estimated: z2Tok,
144
- user_tokens_estimated: uTok,
145
- total_tokens_estimated: totTok,
146
- prefix_cache_eligible_ratio: totTok > 0 ? Number((z1Tok / totTok).toFixed(3)) : 0.0,
147
- },
148
- };
149
- }
150
12
  class SlashMLAPIError extends Error {
151
13
  statusCode;
152
14
  details;
@@ -159,9 +21,9 @@ class SlashMLAPIError extends Error {
159
21
  }
160
22
  exports.SlashMLAPIError = SlashMLAPIError;
161
23
  function getEnv(name) {
162
- const proc = globalThis.process;
163
- if (typeof proc !== "undefined" && proc && proc.env) {
164
- return proc.env[name];
24
+ const g = globalThis;
25
+ if (typeof g.process !== "undefined" && g.process.env) {
26
+ return g.process.env[name];
165
27
  }
166
28
  return undefined;
167
29
  }
@@ -315,7 +177,7 @@ class MemoryClient {
315
177
  const headers = {
316
178
  Accept: "application/json",
317
179
  "Content-Type": "application/json",
318
- "User-Agent": "slashml-memory-ts/1.0.9",
180
+ "User-Agent": "slashml-memory-ts/1.0.11",
319
181
  };
320
182
  if (this.apiKey) {
321
183
  headers.Authorization = `Bearer ${this.apiKey}`;
@@ -372,54 +234,23 @@ class MemoryClient {
372
234
  // ---------------------------------------------------------------------------
373
235
  async ingest(documents, options = {}) {
374
236
  const docs = typeof documents === "string" ? [documents] : Array.from(documents);
375
- const meta = { ...(options.metadata ?? {}) };
376
- const effectiveTier = options.record_tier ?? options.recordTier ?? meta.record_tier ?? meta.tier;
377
- if (effectiveTier)
378
- meta.record_tier = String(effectiveTier);
379
- let effectiveSlot = options.slot_key ?? options.slotKey ?? meta.slot_key;
380
- if (!effectiveSlot && typeof documents === "string") {
381
- effectiveSlot = extractCanonicalSlotKey(documents, meta) ?? undefined;
382
- }
383
- if (effectiveSlot)
384
- meta.slot_key = String(effectiveSlot);
385
- if (options.scope) {
386
- meta.scope = options.scope instanceof RuleScope ? options.scope.toJSON() : options.scope;
387
- }
388
- if (options.contrastive) {
389
- meta.contrastive = {
390
- do: options.contrastive.do,
391
- dont: options.contrastive.dont,
392
- context: options.contrastive.context,
393
- };
394
- }
395
237
  return this.request("POST", "/v1/memory/ingest", {
396
238
  jsonBody: {
397
239
  namespace: options.namespace ?? "default",
398
240
  model: options.model ?? this.model,
399
241
  documents: docs,
400
- metadata: meta,
401
- ...(meta.record_tier ? { record_tier: meta.record_tier } : {}),
402
- ...(meta.slot_key ? { slot_key: meta.slot_key } : {}),
242
+ metadata: options.metadata ?? {},
403
243
  },
404
244
  });
405
245
  }
406
246
  async query(prompt, options = {}) {
407
- const payload = {
408
- namespace: options.namespace ?? "default",
409
- model: options.model ?? this.model,
410
- prompt,
411
- query: prompt,
412
- top_k: options.top_k ?? 5,
413
- };
414
- const effectiveTier = options.record_tier ?? options.recordTier;
415
- if (effectiveTier)
416
- payload.record_tier = String(effectiveTier);
417
- if (options.context)
418
- payload.context = options.context;
419
- if (options.include_rules !== undefined)
420
- payload.include_rules = Boolean(options.include_rules);
421
247
  return this.request("POST", "/v1/memory/query", {
422
- jsonBody: payload,
248
+ jsonBody: {
249
+ namespace: options.namespace ?? "default",
250
+ model: options.model ?? this.model,
251
+ prompt,
252
+ top_k: options.top_k ?? 5,
253
+ },
423
254
  });
424
255
  }
425
256
  async forget(target, options = {}) {
@@ -484,66 +315,6 @@ class MemoryClient {
484
315
  });
485
316
  }
486
317
  // ---------------------------------------------------------------------------
487
- // Phase 30 Dual-Tier & Prompt-Cache Features
488
- // ---------------------------------------------------------------------------
489
- async addRule(text, options = {}) {
490
- const compiled = compileContrastiveRule(text, options.rule_id || options.ruleId, options.scope);
491
- if (options.do)
492
- compiled.do = options.do;
493
- if (options.dont)
494
- compiled.dont = options.dont;
495
- const meta = {
496
- ...(options.metadata ?? {}),
497
- rule_id: compiled.rule_id,
498
- scope: compiled.scope instanceof RuleScope ? compiled.scope.toJSON() : compiled.scope,
499
- contrastive: { do: compiled.do, dont: compiled.dont },
500
- record_tier: "rule",
501
- };
502
- return this.ingest(text, {
503
- record_tier: "rule",
504
- metadata: meta,
505
- scope: compiled.scope,
506
- contrastive: compiled,
507
- });
508
- }
509
- async add_rule(text, options = {}) {
510
- return this.addRule(text, options);
511
- }
512
- async getCacheAlignedPrompt(userTurn, options = {}) {
513
- const rulesRes = await this.query(userTurn, {
514
- top_k: 20,
515
- record_tier: "rule",
516
- context: options.activeContext,
517
- });
518
- const rawRules = rulesRes?.results || rulesRes?.memories || [];
519
- const rulesList = rawRules.map((r) => {
520
- const rMeta = r.metadata || {};
521
- const cInfo = rMeta.contrastive || {};
522
- const sInfo = rMeta.scope || {};
523
- return {
524
- rule_id: String(r.id || rMeta.rule_id || "rule"),
525
- do: String(cInfo.do || r.text || ""),
526
- dont: String(cInfo.dont || ""),
527
- context: String(cInfo.context || ""),
528
- scope: new RuleScope(sInfo),
529
- raw_text: String(r.text || ""),
530
- };
531
- });
532
- const factsRes = await this.query(userTurn, {
533
- top_k: options.top_k || 5,
534
- record_tier: "fact",
535
- });
536
- const rawFacts = factsRes?.results || factsRes?.memories || [];
537
- const factsList = rawFacts.map((f) => String(f.text || f.memory || ""));
538
- return formatCacheAlignedPrompt(rulesList, factsList, userTurn, {
539
- activeContext: options.activeContext,
540
- enableCacheBreakpoint: options.enableCacheBreakpoint ?? true,
541
- });
542
- }
543
- async get_cache_aligned_prompt(userTurn, options = {}) {
544
- return this.getCacheAlignedPrompt(userTurn, options);
545
- }
546
- // ---------------------------------------------------------------------------
547
318
  // Mem0-Compatible REST Endpoints (/v1/memories/*)
548
319
  // ---------------------------------------------------------------------------
549
320
  async add(messages, options = {}) {
@@ -553,26 +324,6 @@ class MemoryClient {
553
324
  : Array.isArray(messages)
554
325
  ? messages
555
326
  : [messages];
556
- const meta = { ...(options.metadata ?? {}) };
557
- const effectiveTier = options.record_tier ?? options.recordTier ?? meta.record_tier ?? meta.tier;
558
- if (effectiveTier)
559
- meta.record_tier = String(effectiveTier);
560
- let effectiveSlot = options.slot_key ?? options.slotKey ?? meta.slot_key;
561
- if (!effectiveSlot && typeof messages === "string") {
562
- effectiveSlot = extractCanonicalSlotKey(messages, meta) ?? undefined;
563
- }
564
- if (effectiveSlot)
565
- meta.slot_key = String(effectiveSlot);
566
- if (options.scope) {
567
- meta.scope = options.scope instanceof RuleScope ? options.scope.toJSON() : options.scope;
568
- }
569
- if (options.contrastive) {
570
- meta.contrastive = {
571
- do: options.contrastive.do,
572
- dont: options.contrastive.dont,
573
- context: options.contrastive.context,
574
- };
575
- }
576
327
  const payload = {
577
328
  messages: normalizedMessages,
578
329
  ...(typeof messages === "string" ? { text: messages } : {}),
@@ -580,9 +331,7 @@ class MemoryClient {
580
331
  agent_id: options.agent_id ?? options.agentId ?? null,
581
332
  app_id: options.app_id ?? options.appId ?? null,
582
333
  run_id: options.run_id ?? options.runId ?? null,
583
- metadata: meta,
584
- ...(meta.record_tier ? { record_tier: meta.record_tier } : {}),
585
- ...(meta.slot_key ? { slot_key: meta.slot_key } : {}),
334
+ metadata: options.metadata ?? {},
586
335
  infer: options.infer ?? true,
587
336
  model: this.model,
588
337
  };
package/dist/index.mjs CHANGED
@@ -6,7 +6,6 @@ export const {
6
6
  DEFAULT_BASE_URL,
7
7
  DEFAULT_MODEL,
8
8
  DEFAULT_TIMEOUT_MS,
9
- RuleScope,
10
9
  SlashMLAPIError,
11
10
  ProjectManager,
12
11
  MemoryClient,
@@ -17,9 +16,6 @@ export const {
17
16
  SlashMLClient,
18
17
  AsyncSlashMLMemory,
19
18
  AsyncSlashMLClient,
20
- extractCanonicalSlotKey,
21
- compileContrastiveRule,
22
- formatCacheAlignedPrompt,
23
19
  } = cjs;
24
20
 
25
21
  export default cjs;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slashml/memory",
3
- "version": "1.0.9",
3
+ "version": "1.0.11",
4
4
  "description": "Official HTTP TypeScript & Node.js SDK for / ml (https://api.slashml.ai)",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://slashml.ai",
@@ -31,7 +31,7 @@
31
31
  "LICENSE"
32
32
  ],
33
33
  "scripts": {
34
- "build": "tsc && node -e \"const fs = require('node:fs'); const code = 'import { createRequire } from \\\"node:module\\\";\\nconst require = createRequire(import.meta.url);\\nconst cjs = require(\\\"./index.js\\\");\\n\\nexport const {\\n DEFAULT_BASE_URL,\\n DEFAULT_MODEL,\\n DEFAULT_TIMEOUT_MS,\\n RuleScope,\\n SlashMLAPIError,\\n ProjectManager,\\n MemoryClient,\\n Memory,\\n AsyncMemoryClient,\\n AsyncMemory,\\n SlashMLMemory,\\n SlashMLClient,\\n AsyncSlashMLMemory,\\n AsyncSlashMLClient,\\n extractCanonicalSlotKey,\\n compileContrastiveRule,\\n formatCacheAlignedPrompt,\\n} = cjs;\\n\\nexport default cjs;\\n'; fs.writeFileSync('dist/index.mjs', code);\"",
34
+ "build": "tsc && node -e \"const fs = require('node:fs'); const code = 'import { createRequire } from \\\"node:module\\\";\\nconst require = createRequire(import.meta.url);\\nconst cjs = require(\\\"./index.js\\\");\\n\\nexport const {\\n DEFAULT_BASE_URL,\\n DEFAULT_MODEL,\\n DEFAULT_TIMEOUT_MS,\\n SlashMLAPIError,\\n ProjectManager,\\n MemoryClient,\\n Memory,\\n AsyncMemoryClient,\\n AsyncMemory,\\n SlashMLMemory,\\n SlashMLClient,\\n AsyncSlashMLMemory,\\n AsyncSlashMLClient,\\n} = cjs;\\n\\nexport default cjs;\\n'; fs.writeFileSync('dist/index.mjs', code);\"",
35
35
  "test": "node --test test/sdk.test.js"
36
36
  },
37
37
  "engines": {