@slashml/memory 1.0.4 → 1.0.6

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/bin/cli.js CHANGED
@@ -10,7 +10,7 @@ const readline = require("readline");
10
10
 
11
11
  const DEFAULT_BASE_URL = "https://api.slashml.ai";
12
12
  const DEFAULT_CONSOLE_URL = "https://app.slashml.ai";
13
- const PACKAGE_VERSION = "1.0.4";
13
+ const PACKAGE_VERSION = "1.0.6";
14
14
 
15
15
  function printHelp() {
16
16
  console.log(`@slashml/memory v${PACKAGE_VERSION} — Official CLI & MCP Stdio Server for / ml (SlashML · https://slashml.ai)
@@ -121,6 +121,46 @@ function assertCliWorkEmail(rawEmail) {
121
121
  return cleaned;
122
122
  }
123
123
 
124
+ function resolveFallbackApiKey() {
125
+ const home = os.homedir();
126
+ const configCandidates = [
127
+ path.join(home, ".gemini", "config", "mcp_config.json"),
128
+ path.join(home, ".claude", "settings.json"),
129
+ path.join(home, ".cursor", "mcp.json"),
130
+ path.join(home, ".codeium", "windsurf", "mcp_config.json"),
131
+ ];
132
+ for (const cfgPath of configCandidates) {
133
+ try {
134
+ if (!fs.existsSync(cfgPath)) continue;
135
+ const parsed = JSON.parse(fs.readFileSync(cfgPath, "utf8"));
136
+ if (parsed && parsed.env && parsed.env.SLASHML_API_KEY) {
137
+ return String(parsed.env.SLASHML_API_KEY).trim();
138
+ }
139
+ const servers = parsed && parsed.mcpServers;
140
+ if (servers && typeof servers === "object") {
141
+ const entry = servers["ml-memory"] || servers["/ml-memory"] || servers["slashml"];
142
+ if (entry && entry.env && entry.env.SLASHML_API_KEY) {
143
+ return String(entry.env.SLASHML_API_KEY).trim();
144
+ }
145
+ }
146
+ } catch {
147
+ // ignore unreadable config
148
+ }
149
+ }
150
+ try {
151
+ const envPath = path.join(process.cwd(), ".env");
152
+ if (fs.existsSync(envPath)) {
153
+ const m = fs.readFileSync(envPath, "utf8").match(/^SLASHML_API_KEY=(.+)$/m);
154
+ if (m && m[1]) {
155
+ return m[1].trim().replace(/^["']|["']$/g, "");
156
+ }
157
+ }
158
+ } catch {
159
+ // ignore
160
+ }
161
+ return null;
162
+ }
163
+
124
164
  function parseCliArgs(argv) {
125
165
  let isHelp = false;
126
166
  let isVersion = false;
@@ -132,12 +172,14 @@ function parseCliArgs(argv) {
132
172
  let userId = process.env.SLASHML_USER_ID || "default";
133
173
  let codeOnly = false;
134
174
  let codeMode = false;
175
+ let passiveWrites = process.env.SLASHML_PASSIVE_WRITES === "1";
135
176
  let repo = null;
136
177
  let signupEmail = null;
137
178
  let verifyEmail = null;
138
179
  let verifyCode = null;
139
180
  let writeEnv = false;
140
181
  let isHook = false;
182
+ let hookEvent = null;
141
183
  let isInstallHooks = false;
142
184
  let isStatus = false;
143
185
  let jsonOutput = false;
@@ -152,6 +194,8 @@ function parseCliArgs(argv) {
152
194
  isInit = true;
153
195
  } else if (arg === "--hook" || arg === "hook") {
154
196
  isHook = true;
197
+ } else if (arg === "--hook-event" && i + 1 < argv.length) {
198
+ hookEvent = argv[++i];
155
199
  } else if (arg === "--install-hooks" || arg === "install-hooks") {
156
200
  isInstallHooks = true;
157
201
  } else if (arg === "--status" || arg === "status") {
@@ -185,8 +229,13 @@ function parseCliArgs(argv) {
185
229
  codeOnly = true;
186
230
  } else if (arg === "--code-mode") {
187
231
  codeMode = true;
232
+ } else if (arg === "--passive-writes" || arg === "--no-add-memory") {
233
+ passiveWrites = true;
188
234
  }
189
235
  }
236
+ if (!apiKey) {
237
+ apiKey = resolveFallbackApiKey();
238
+ }
190
239
  return {
191
240
  isHelp,
192
241
  isVersion,
@@ -198,12 +247,14 @@ function parseCliArgs(argv) {
198
247
  userId,
199
248
  codeOnly,
200
249
  codeMode,
250
+ passiveWrites,
201
251
  repo,
202
252
  signupEmail,
203
253
  verifyEmail,
204
254
  verifyCode,
205
255
  writeEnv,
206
256
  isHook,
257
+ hookEvent,
207
258
  isInstallHooks,
208
259
  isStatus,
209
260
  jsonOutput,
@@ -466,7 +517,7 @@ function installAmbientHooks(apiKey) {
466
517
  settings.hooks[eventName] = [
467
518
  {
468
519
  matcher: ".*",
469
- hooks: [{ type: "command", command: hookCmd, timeout: 5 }],
520
+ hooks: [{ type: "command", command: hookCmd, timeout: 10 }],
470
521
  },
471
522
  ];
472
523
  }
@@ -475,6 +526,57 @@ function installAmbientHooks(apiKey) {
475
526
  }
476
527
  fs.writeFileSync(claudeSettingsPath, JSON.stringify(settings, null, 2) + "\n", "utf8");
477
528
  console.log(`Configured / ml ambient lifecycle hooks in ${claudeSettingsPath}`);
529
+
530
+ // Also configure Gemini CLI plugin hooks if ~/.gemini/config exists
531
+ const geminiPluginDir = path.join(home, ".gemini", "config", "plugins", "slashml-memory");
532
+ if (fs.existsSync(path.join(home, ".gemini", "config")) || fs.existsSync(geminiPluginDir)) {
533
+ fs.mkdirSync(geminiPluginDir, { recursive: true });
534
+ const geminiHooksPath = path.join(geminiPluginDir, "hooks.json");
535
+ const geminiHooks = {
536
+ "slashml-ambient-memory": {
537
+ PreInvocation: [
538
+ {
539
+ type: "command",
540
+ command: `${hookCmd} --hook-event PreInvocation`,
541
+ timeout: 10,
542
+ },
543
+ ],
544
+ PreToolUse: [
545
+ {
546
+ matcher: "run_command|edit_file|write_file",
547
+ hooks: [
548
+ {
549
+ type: "command",
550
+ command: `${hookCmd} --hook-event PreToolUse`,
551
+ timeout: 10,
552
+ },
553
+ ],
554
+ },
555
+ ],
556
+ PostToolUse: [
557
+ {
558
+ matcher: "run_command|edit_file|write_file",
559
+ hooks: [
560
+ {
561
+ type: "command",
562
+ command: `${hookCmd} --hook-event PostToolUse`,
563
+ timeout: 10,
564
+ },
565
+ ],
566
+ },
567
+ ],
568
+ Stop: [
569
+ {
570
+ type: "command",
571
+ command: `${hookCmd} --hook-event Stop`,
572
+ timeout: 10,
573
+ },
574
+ ],
575
+ },
576
+ };
577
+ fs.writeFileSync(geminiHooksPath, JSON.stringify(geminiHooks, null, 2) + "\n", "utf8");
578
+ console.log(`Configured / ml ambient lifecycle hooks in ${geminiHooksPath}`);
579
+ }
478
580
  }
479
581
 
480
582
  function getTelemetryPath() {
@@ -648,6 +750,141 @@ async function runStatusCommand(opts) {
648
750
  console.log(` # Amnesia Episodes Intercepted : ${amnesiaIntercepted}`);
649
751
  }
650
752
 
753
+ function extractLastPlannerResponseFromTranscript(transcriptPath) {
754
+ if (!transcriptPath || typeof transcriptPath !== "string") return "";
755
+ try {
756
+ if (!fs.existsSync(transcriptPath)) return "";
757
+ const stat = fs.statSync(transcriptPath);
758
+ const maxBytes = 65536;
759
+ const start = Math.max(0, stat.size - maxBytes);
760
+ const len = stat.size - start;
761
+ if (len <= 0) return "";
762
+ const fd = fs.openSync(transcriptPath, "r");
763
+ const buf = Buffer.alloc(len);
764
+ fs.readSync(fd, buf, 0, len, start);
765
+ fs.closeSync(fd);
766
+ const lines = buf.toString("utf8").split(/\r?\n/);
767
+ for (let i = lines.length - 1; i >= 0; i--) {
768
+ const line = lines[i].trim();
769
+ if (!line || !line.startsWith("{")) continue;
770
+ try {
771
+ const entry = JSON.parse(line);
772
+ if (!entry) continue;
773
+ if (entry.type === "PLANNER_RESPONSE" && typeof entry.content === "string" && entry.content.trim()) {
774
+ return entry.content.trim();
775
+ }
776
+ const msgObj = entry.message && typeof entry.message === "object" ? entry.message : entry;
777
+ if (msgObj && msgObj.role === "assistant") {
778
+ if (typeof msgObj.content === "string" && msgObj.content.trim()) {
779
+ return msgObj.content.trim();
780
+ }
781
+ if (Array.isArray(msgObj.content)) {
782
+ const textParts = msgObj.content
783
+ .filter((b) => b && (b.type === "text" || typeof b.text === "string"))
784
+ .map((b) => String(b.text || "").trim())
785
+ .filter(Boolean);
786
+ if (textParts.length > 0) {
787
+ return textParts.join("\n").trim();
788
+ }
789
+ }
790
+ }
791
+ } catch {
792
+ // ignore partial line at start of buffer
793
+ }
794
+ }
795
+ } catch {
796
+ // ignore transcript read errors
797
+ }
798
+ return "";
799
+ }
800
+
801
+ function extractWhisperedContextFromCurrentTurn(transcriptPath) {
802
+ if (!transcriptPath || typeof transcriptPath !== "string") return { ids: [], blocks: [] };
803
+ const ids = new Set();
804
+ const blocks = new Set();
805
+ try {
806
+ if (!fs.existsSync(transcriptPath)) return { ids: [], blocks: [] };
807
+ const stat = fs.statSync(transcriptPath);
808
+ const maxBytes = 65536;
809
+ const start = Math.max(0, stat.size - maxBytes);
810
+ const len = stat.size - start;
811
+ if (len <= 0) return { ids: [], blocks: [] };
812
+ const fd = fs.openSync(transcriptPath, "r");
813
+ const buf = Buffer.alloc(len);
814
+ fs.readSync(fd, buf, 0, len, start);
815
+ fs.closeSync(fd);
816
+ const lines = buf.toString("utf8").split(/\r?\n/);
817
+ for (let i = lines.length - 1; i >= 0; i--) {
818
+ const line = lines[i].trim();
819
+ if (!line || !line.startsWith("{")) continue;
820
+ try {
821
+ const entry = JSON.parse(line);
822
+ if (!entry) continue;
823
+ if (entry.type === "USER_INPUT") break;
824
+ const content = typeof entry.content === "string" ? entry.content : "";
825
+ const memTagMatches = content.match(/<memory>[\s\S]*?<\/memory>/gi);
826
+ if (memTagMatches) {
827
+ for (const tag of memTagMatches) blocks.add(tag.trim());
828
+ }
829
+ if (
830
+ content.includes("<memory>") ||
831
+ content.includes("[MEMORY WHISPER]") ||
832
+ content.includes("[MEMORY INTERVENTION]") ||
833
+ content.includes("[MEMORY CONTEXT]")
834
+ ) {
835
+ const matches = content.match(/\bmem_[a-z0-9_]+\b/gi);
836
+ if (matches) {
837
+ for (const m of matches) ids.add(m);
838
+ }
839
+ }
840
+ } catch {
841
+ // ignore partial line at start of buffer
842
+ }
843
+ }
844
+ } catch {
845
+ // ignore transcript read errors
846
+ }
847
+ return { ids: Array.from(ids), blocks: Array.from(blocks) };
848
+ }
849
+
850
+ function writeDefaultHookOutput(isGeminiHook, rawEventName) {
851
+ if (isGeminiHook && rawEventName === "PreToolUse") {
852
+ process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
853
+ } else {
854
+ process.stdout.write("{}\n");
855
+ }
856
+ }
857
+
858
+ function resolveHookProjectId(opts, payload) {
859
+ const explicit = [
860
+ payload && payload.project_id,
861
+ payload && payload.projectId,
862
+ process.env.SLASHML_PROJECT_ID,
863
+ ];
864
+ for (const val of explicit) {
865
+ if (typeof val === "string" && val.trim()) {
866
+ return val.trim();
867
+ }
868
+ }
869
+ const dirCandidates = [
870
+ opts && opts.repo,
871
+ payload && Array.isArray(payload.workspacePaths) && payload.workspacePaths[0],
872
+ payload && Array.isArray(payload.workspace_paths) && payload.workspace_paths[0],
873
+ payload && payload.cwd,
874
+ process.cwd(),
875
+ ];
876
+ for (const dir of dirCandidates) {
877
+ if (typeof dir === "string" && dir.trim()) {
878
+ const cleaned = dir.trim().replace(/[\\/]+$/, "");
879
+ const base = path.basename(cleaned);
880
+ if (base && base !== "." && base !== "/") {
881
+ return base;
882
+ }
883
+ }
884
+ }
885
+ return "";
886
+ }
887
+
651
888
  async function runAmbientHookMode(opts) {
652
889
  const crypto = require("crypto");
653
890
  const chunks = [];
@@ -655,8 +892,9 @@ async function runAmbientHookMode(opts) {
655
892
  chunks.push(Buffer.from(chunk));
656
893
  }
657
894
  const rawInput = Buffer.concat(chunks).toString("utf8").trim();
895
+ const cliEvent = opts.hookEvent ? String(opts.hookEvent).trim() : "";
658
896
  if (!rawInput) {
659
- process.stdout.write("{}\n");
897
+ writeDefaultHookOutput(Boolean(cliEvent), cliEvent);
660
898
  return;
661
899
  }
662
900
  const rawEventTokens = estimateTokens(rawInput);
@@ -664,98 +902,292 @@ async function runAmbientHookMode(opts) {
664
902
  try {
665
903
  payload = JSON.parse(rawInput);
666
904
  } catch {
667
- payload = { hook_event_name: "UserPromptSubmit", prompt: rawInput };
905
+ payload = { hook_event_name: cliEvent || "UserPromptSubmit", prompt: rawInput };
668
906
  }
669
907
 
670
- const hookEvent = String(
671
- payload.hook_event_name || payload.hook_event || payload.event || "UserPromptSubmit"
908
+ const isGeminiHook = Boolean(
909
+ cliEvent === "PreInvocation" ||
910
+ payload.invocationNum !== undefined ||
911
+ payload.toolCall !== undefined ||
912
+ payload.terminationReason !== undefined ||
913
+ payload.workspacePaths !== undefined ||
914
+ payload.artifactDirectoryPath !== undefined ||
915
+ payload.conversationId !== undefined
672
916
  );
673
- const toolName = payload.tool_name ? String(payload.tool_name).trim() : null;
674
917
 
675
- // Skip read-only tools
918
+ let rawEventName = String(
919
+ cliEvent || payload.hook_event_name || payload.hook_event || payload.event || ""
920
+ ).trim();
921
+ if (!rawEventName) {
922
+ if (isGeminiHook) {
923
+ if (payload.toolCall !== undefined) {
924
+ rawEventName =
925
+ payload.toolResponse !== undefined || payload.toolResult !== undefined
926
+ ? "PostToolUse"
927
+ : "PreToolUse";
928
+ } else if (payload.terminationReason !== undefined || payload.executionNum !== undefined) {
929
+ rawEventName = "Stop";
930
+ } else {
931
+ rawEventName = "PreInvocation";
932
+ }
933
+ } else {
934
+ rawEventName = "UserPromptSubmit";
935
+ }
936
+ }
937
+
938
+ const hookEvent = rawEventName === "PreInvocation" ? "UserPromptSubmit" : rawEventName;
939
+
940
+ // On Gemini CLI Stop, only evaluate normal completion turns (NO_TOOL_CALL)
941
+ if (isGeminiHook && rawEventName === "Stop") {
942
+ if (payload.terminationReason && payload.terminationReason !== "NO_TOOL_CALL") {
943
+ writeDefaultHookOutput(isGeminiHook, rawEventName);
944
+ return;
945
+ }
946
+ }
947
+
948
+ // On Claude Code Stop, never re-block if stop_hook_active is already true
949
+ if (!isGeminiHook && rawEventName === "Stop" && payload.stop_hook_active) {
950
+ writeDefaultHookOutput(isGeminiHook, rawEventName);
951
+ return;
952
+ }
953
+
954
+ const toolCallObj =
955
+ payload.toolCall && typeof payload.toolCall === "object" ? payload.toolCall : null;
956
+ const toolName =
957
+ String(payload.tool_name || (toolCallObj && toolCallObj.name) || "").trim() || null;
958
+
959
+ const toolIn =
960
+ (payload.tool_input && typeof payload.tool_input === "object" ? payload.tool_input : null) ||
961
+ (toolCallObj && toolCallObj.args && typeof toolCallObj.args === "object"
962
+ ? toolCallObj.args
963
+ : null);
964
+
965
+ const dedupPath =
966
+ process.env.SLASHML_HOOK_STATE_PATH ||
967
+ path.join(os.homedir(), ".slashml", "hook_state.json");
968
+ let dedupState = { hashes: [] };
969
+ try {
970
+ if (fs.existsSync(dedupPath)) {
971
+ dedupState = JSON.parse(fs.readFileSync(dedupPath, "utf8")) || { hashes: [] };
972
+ }
973
+ } catch {
974
+ dedupState = { hashes: [] };
975
+ }
976
+ const sessionKey = String(
977
+ payload.conversationId ||
978
+ payload.session_id ||
979
+ payload.sessionId ||
980
+ process.env.SLASHML_SESSION_ID ||
981
+ ""
982
+ ).trim();
983
+ const projectId = resolveHookProjectId(opts, payload);
984
+ const scopeStateKey = `${projectId || "_default"}:${sessionKey || "_default"}`;
985
+
986
+ // / ml (SlashML · https://slashml.ai · github.com/slashml-ai/ml-memory · support@slashml.ai)
987
+ function persistPendingToolContext() {
988
+ if (!toolIn || typeof toolIn !== "object") return;
989
+ const refObj = {};
990
+ for (const k of ["file_path", "path", "Path", "command", "CommandLine"]) {
991
+ if (typeof toolIn[k] === "string" && toolIn[k].trim()) {
992
+ refObj[k] = toolIn[k].trim().slice(0, 400);
993
+ }
994
+ }
995
+ if (Object.keys(refObj).length === 0) return;
996
+ if (
997
+ !dedupState.pending_tool_input_by_session ||
998
+ typeof dedupState.pending_tool_input_by_session !== "object"
999
+ ) {
1000
+ dedupState.pending_tool_input_by_session = {};
1001
+ }
1002
+ dedupState.pending_tool_input_by_session[scopeStateKey] = refObj;
1003
+ try {
1004
+ fs.mkdirSync(path.dirname(dedupPath), { recursive: true });
1005
+ fs.writeFileSync(dedupPath, JSON.stringify(dedupState), "utf8");
1006
+ } catch {
1007
+ // ignore state persistence errors
1008
+ }
1009
+ }
1010
+
1011
+ // Skip read-only tools locally
676
1012
  if ((hookEvent === "PreToolUse" || hookEvent === "PostToolUse") && toolName) {
677
1013
  if (HOOK_READ_ONLY_TOOLS.has(toolName.toLowerCase())) {
1014
+ persistPendingToolContext();
678
1015
  recordLocalHookDrop(rawEventTokens);
679
- process.stdout.write("{}\n");
1016
+ writeDefaultHookOutput(isGeminiHook, rawEventName);
680
1017
  return;
681
1018
  }
682
1019
  }
683
1020
 
684
- const toolIn = payload.tool_input && typeof payload.tool_input === "object" ? payload.tool_input : null;
685
1021
  const toolSummary = toolIn
686
- ? toolIn.command || toolIn.CommandLine || toolIn.new_string || toolIn.content || JSON.stringify(toolIn)
1022
+ ? toolIn.command ||
1023
+ toolIn.CommandLine ||
1024
+ toolIn.Replacement ||
1025
+ toolIn.new_string ||
1026
+ toolIn.Content ||
1027
+ toolIn.content ||
1028
+ JSON.stringify(toolIn)
687
1029
  : "";
688
- const deltaText = String(
689
- payload.prompt ||
690
- payload.text ||
691
- payload.user_prompt ||
1030
+
1031
+ if (
1032
+ (hookEvent === "PreToolUse" || hookEvent === "PostToolUse") &&
1033
+ toolName &&
1034
+ /^(bash|run_command|shell)$/i.test(toolName)
1035
+ ) {
1036
+ const cmdCheck = String(toolSummary || "")
1037
+ .trim()
1038
+ .toLowerCase()
1039
+ .replace(/^\s*cd\s+[^&;]+(?:&&|;)\s*/, "")
1040
+ .trim();
1041
+ const isReadOnlyCmd =
1042
+ /^(ls\b|pwd\b|cat\s|head\s|tail\s|grep\s|rg\s|find\s|git\s+(status|log|diff|branch|show|worktree|rev-parse|remote|tag|describe)\b|which\s|whoami\b|stat\s|wc\s)/.test(
1043
+ cmdCheck
1044
+ ) && !/[>]|(\brm\s|\bmv\s|\bcp\s|git\s+(push|commit)|\binstall\b)/.test(cmdCheck);
1045
+ if (isReadOnlyCmd) {
1046
+ persistPendingToolContext();
1047
+ recordLocalHookDrop(rawEventTokens);
1048
+ writeDefaultHookOutput(isGeminiHook, rawEventName);
1049
+ return;
1050
+ }
1051
+ }
1052
+
1053
+ let rawCandidateText = "";
1054
+ if (hookEvent === "PreToolUse") {
1055
+ rawCandidateText = String(toolSummary || "");
1056
+ } else if (hookEvent === "PostToolUse") {
1057
+ const toolResp = payload.tool_response || payload.toolResponse || payload.toolResult;
1058
+ rawCandidateText = String(
1059
+ (toolResp ? (typeof toolResp === "string" ? toolResp : JSON.stringify(toolResp)) : "") ||
1060
+ toolSummary ||
1061
+ ""
1062
+ );
1063
+ } else if (hookEvent === "Stop") {
1064
+ const transcriptFile = payload.transcriptPath || payload.transcript_path;
1065
+ rawCandidateText = String(
692
1066
  payload.last_assistant_message ||
693
- payload.assistant_message ||
694
- payload.response ||
695
- toolSummary ||
696
- (payload.tool_response ? JSON.stringify(payload.tool_response) : "")
697
- )
1067
+ payload.assistant_message ||
1068
+ payload.response ||
1069
+ extractLastPlannerResponseFromTranscript(transcriptFile) ||
1070
+ ""
1071
+ );
1072
+ } else {
1073
+ rawCandidateText = String(
1074
+ payload.prompt || payload.user_prompt || payload.lastUserInput || payload.text || ""
1075
+ );
1076
+ }
1077
+
1078
+ const deltaText = rawCandidateText
698
1079
  .replace(/<thinking>[\s\S]*?<\/thinking>/gi, " ")
1080
+ .replace(/[\u2500-\u257f]+/g, " ")
699
1081
  .replace(/\s+/g, " ")
700
1082
  .trim()
701
1083
  .slice(0, 1024);
702
1084
 
703
- if (!deltaText || deltaText.length < 4 || /^(ok|okay|thanks|thank you|yes|no|sure|cool|lgtm)[.!]*$/i.test(deltaText)) {
1085
+ if (
1086
+ !deltaText ||
1087
+ deltaText.length < 4 ||
1088
+ /^(ok|okay|thanks|thank you|yes|no|sure|cool|lgtm)[.!]*$/i.test(deltaText)
1089
+ ) {
704
1090
  recordLocalHookDrop(rawEventTokens);
705
- process.stdout.write("{}\n");
1091
+ writeDefaultHookOutput(isGeminiHook, rawEventName);
706
1092
  return;
707
1093
  }
708
1094
 
709
- // Event deduplication
710
- const dedupPath =
711
- process.env.SLASHML_HOOK_STATE_PATH ||
712
- path.join(os.homedir(), ".slashml", "hook_state.json");
713
- let dedupState = { hashes: [] };
714
- try {
715
- if (fs.existsSync(dedupPath)) {
716
- dedupState = JSON.parse(fs.readFileSync(dedupPath, "utf8")) || { hashes: [] };
717
- }
718
- } catch {
719
- dedupState = { hashes: [] };
720
- }
1095
+ // Event deduplication (scoped to project/session/step and only persisted for non-actionable noise)
1096
+ const stepKey = String(
1097
+ payload.stepIdx ?? payload.invocationNum ?? payload.executionNum ?? ""
1098
+ );
721
1099
  const deltaHash = crypto
722
1100
  .createHash("sha1")
723
- .update(`${hookEvent}:${toolName || ""}:${deltaText.toLowerCase()}`)
1101
+ .update(
1102
+ `${projectId}:${sessionKey}:${stepKey}:${hookEvent}:${toolName || ""}:${deltaText.toLowerCase()}`
1103
+ )
724
1104
  .digest("hex")
725
1105
  .slice(0, 16);
726
1106
  if (Array.isArray(dedupState.hashes) && dedupState.hashes.includes(deltaHash)) {
727
1107
  recordLocalHookDrop(rawEventTokens);
728
- process.stdout.write("{}\n");
1108
+ writeDefaultHookOutput(isGeminiHook, rawEventName);
729
1109
  return;
730
1110
  }
731
- dedupState.hashes = [...(Array.isArray(dedupState.hashes) ? dedupState.hashes.slice(-63) : []), deltaHash];
732
- try {
733
- fs.mkdirSync(path.dirname(dedupPath), { recursive: true });
734
- fs.writeFileSync(dedupPath, JSON.stringify(dedupState), "utf8");
735
- } catch {
736
- // ignore state persistence errors
737
- }
738
1111
 
739
1112
  if (!opts.apiKey) {
740
1113
  recordLocalHookDrop(rawEventTokens);
741
- process.stdout.write("{}\n");
1114
+ writeDefaultHookOutput(isGeminiHook, rawEventName);
742
1115
  return;
743
1116
  }
744
1117
 
745
1118
  const telem = loadHookTelemetry();
746
1119
  const cleanTokens = estimateTokens(deltaText);
747
1120
  const strippedTokens = Math.max(0, rawEventTokens - cleanTokens);
1121
+ if (!dedupState.whispered_by_session || typeof dedupState.whispered_by_session !== "object") {
1122
+ dedupState.whispered_by_session = {};
1123
+ }
1124
+ if (!dedupState.whispered_blocks_by_session || typeof dedupState.whispered_blocks_by_session !== "object") {
1125
+ dedupState.whispered_blocks_by_session = {};
1126
+ }
1127
+ const whisperKey = sessionKey || scopeStateKey;
1128
+ const isMidTurnContinuation =
1129
+ rawEventName === "PreInvocation" && Number(payload.invocationNum || 1) > 1;
1130
+ if (hookEvent === "UserPromptSubmit" && !isMidTurnContinuation && whisperKey) {
1131
+ dedupState.whispered_by_session[whisperKey] = [];
1132
+ dedupState.whispered_blocks_by_session[whisperKey] = [];
1133
+ }
1134
+ const transcriptWhispered = extractWhisperedContextFromCurrentTurn(
1135
+ payload.transcriptPath || payload.transcript_path
1136
+ );
1137
+ const sessionWhispered =
1138
+ whisperKey && Array.isArray(dedupState.whispered_by_session[whisperKey])
1139
+ ? dedupState.whispered_by_session[whisperKey]
1140
+ : [];
1141
+ const sessionWhisperedBlocks =
1142
+ whisperKey && Array.isArray(dedupState.whispered_blocks_by_session[whisperKey])
1143
+ ? dedupState.whispered_blocks_by_session[whisperKey]
1144
+ : [];
1145
+ const whisperedMemoryIds = Array.from(new Set([...transcriptWhispered.ids, ...sessionWhispered]));
1146
+ const whisperedBlocks = Array.from(new Set([...transcriptWhispered.blocks, ...sessionWhisperedBlocks]));
1147
+ const streamTextForIntervene =
1148
+ (hookEvent === "Stop" || hookEvent === "PreToolUse") &&
1149
+ whisperedBlocks.length > 0 &&
1150
+ !deltaText.toLowerCase().includes("<memory>")
1151
+ ? `${whisperedBlocks.join("\n")}\n${deltaText}`
1152
+ : deltaText;
1153
+
1154
+ let effectiveToolIn = toolIn || null;
1155
+ if (
1156
+ !effectiveToolIn &&
1157
+ dedupState.pending_tool_input_by_session &&
1158
+ typeof dedupState.pending_tool_input_by_session === "object" &&
1159
+ dedupState.pending_tool_input_by_session[scopeStateKey]
1160
+ ) {
1161
+ effectiveToolIn = dedupState.pending_tool_input_by_session[scopeStateKey];
1162
+ delete dedupState.pending_tool_input_by_session[scopeStateKey];
1163
+ } else if (
1164
+ effectiveToolIn &&
1165
+ dedupState.pending_tool_input_by_session &&
1166
+ typeof dedupState.pending_tool_input_by_session === "object"
1167
+ ) {
1168
+ delete dedupState.pending_tool_input_by_session[scopeStateKey];
1169
+ }
748
1170
 
749
1171
  try {
750
1172
  const resp = await apiRequest(opts, "POST", "/v1/memory/intervene", {
751
1173
  hook_event_name: hookEvent,
752
- prompt: payload.prompt || deltaText,
753
- text: deltaText,
1174
+ prompt: payload.prompt || payload.lastUserInput || deltaText,
1175
+ text: streamTextForIntervene,
1176
+ ...(hookEvent === "Stop"
1177
+ ? {
1178
+ last_assistant_message: deltaText,
1179
+ stop_hook_active: Boolean(payload.stop_hook_active),
1180
+ }
1181
+ : {}),
754
1182
  tool_name: toolName,
755
- tool_input: payload.tool_input || null,
756
- tool_response: payload.tool_response || null,
1183
+ tool_input: effectiveToolIn,
1184
+ tool_response: payload.tool_response || payload.toolResponse || null,
1185
+ whispered_memory_ids: whisperedMemoryIds,
1186
+ commit_writes: isMidTurnContinuation ? false : true,
757
1187
  model: process.env.SLASHML_MODEL || undefined,
758
1188
  user_id: opts.userId,
1189
+ ...(projectId ? { project_id: projectId } : {}),
1190
+ ...(sessionKey ? { session_id: sessionKey } : {}),
759
1191
  client_raw_tokens_delta: (telem.pending_raw_tokens_delta || 0) + strippedTokens,
760
1192
  client_dropped_tokens_delta: (telem.pending_dropped_tokens_delta || 0) + strippedTokens,
761
1193
  client_dropped_events_delta: telem.pending_dropped_events_delta || 0,
@@ -775,20 +1207,97 @@ async function runAmbientHookMode(opts) {
775
1207
  if (resp.write_novelty_action === "SUPERSEDES") {
776
1208
  telem.memories_superseded = (telem.memories_superseded || 0) + 1;
777
1209
  }
1210
+ dedupState.hashes = [];
778
1211
  }
779
1212
  if (resp.should_intervene) {
780
1213
  telem.amnesia_episodes_intercepted = (telem.amnesia_episodes_intercepted || 0) + 1;
1214
+ const triggeredIds = [
1215
+ ...(Array.isArray(resp.violated_memory_ids) ? resp.violated_memory_ids : []),
1216
+ ...(resp.violated_memory_id ? [resp.violated_memory_id] : []),
1217
+ ...(resp.triggered_memory_id ? [resp.triggered_memory_id] : []),
1218
+ ].filter(Boolean);
1219
+ if (whisperKey && triggeredIds.length > 0) {
1220
+ const prev = Array.isArray(dedupState.whispered_by_session[whisperKey])
1221
+ ? dedupState.whispered_by_session[whisperKey]
1222
+ : [];
1223
+ const merged = Array.from(new Set([...prev, ...triggeredIds]));
1224
+ dedupState.whispered_by_session[whisperKey] = merged.slice(-16);
1225
+ }
1226
+ if (whisperKey && resp.intervention_message) {
1227
+ const msgTags = String(resp.intervention_message).match(/<memory>[\s\S]*?<\/memory>/gi);
1228
+ if (msgTags) {
1229
+ const prevBlocks = Array.isArray(dedupState.whispered_blocks_by_session[whisperKey])
1230
+ ? dedupState.whispered_blocks_by_session[whisperKey]
1231
+ : [];
1232
+ const nextBlocks = Array.from(new Set([...prevBlocks, ...msgTags.map((t) => t.trim())]));
1233
+ dedupState.whispered_blocks_by_session[whisperKey] = nextBlocks.slice(-8);
1234
+ }
1235
+ }
781
1236
  }
782
1237
  } else {
783
1238
  telem.noise_tokens_filtered = (telem.noise_tokens_filtered || 0) + rawEventTokens;
784
1239
  telem.events_filtered_noise = (telem.events_filtered_noise || 0) + 1;
1240
+ dedupState.hashes = [
1241
+ ...(Array.isArray(dedupState.hashes) ? dedupState.hashes.slice(-63) : []),
1242
+ deltaHash,
1243
+ ];
1244
+ }
1245
+ try {
1246
+ fs.mkdirSync(path.dirname(dedupPath), { recursive: true });
1247
+ fs.writeFileSync(dedupPath, JSON.stringify(dedupState), "utf8");
1248
+ } catch {
1249
+ // ignore state persistence errors
785
1250
  }
786
1251
  saveHookTelemetry(telem);
787
- const out = resp && typeof resp.hook_output === "object" && resp.hook_output ? resp.hook_output : {};
1252
+
1253
+ let out = {};
1254
+ if (isGeminiHook) {
1255
+ if (rawEventName === "PreInvocation") {
1256
+ if (resp && resp.should_intervene && resp.intervention_message) {
1257
+ out = {
1258
+ injectSteps: [
1259
+ {
1260
+ ephemeralMessage: resp.intervention_message,
1261
+ },
1262
+ ],
1263
+ };
1264
+ }
1265
+ } else if (rawEventName === "PreToolUse") {
1266
+ if (
1267
+ resp &&
1268
+ resp.should_intervene &&
1269
+ resp.intervention_severity === "BLOCK" &&
1270
+ resp.intervention_message
1271
+ ) {
1272
+ out = {
1273
+ decision: "deny",
1274
+ reason: resp.intervention_message,
1275
+ };
1276
+ } else {
1277
+ out = {
1278
+ decision: "allow",
1279
+ };
1280
+ }
1281
+ } else if (rawEventName === "Stop") {
1282
+ if (
1283
+ resp &&
1284
+ resp.should_intervene &&
1285
+ resp.intervention_severity === "BLOCK" &&
1286
+ resp.intervention_message
1287
+ ) {
1288
+ out = {
1289
+ decision: "continue",
1290
+ reason: resp.intervention_message,
1291
+ };
1292
+ }
1293
+ }
1294
+ } else {
1295
+ out = resp && typeof resp.hook_output === "object" && resp.hook_output ? resp.hook_output : {};
1296
+ }
788
1297
  process.stdout.write(JSON.stringify(out) + "\n");
789
1298
  } catch {
790
1299
  // Fail-open on network errors so the IDE is never blocked
791
- process.stdout.write("{}\n");
1300
+ writeDefaultHookOutput(isGeminiHook, rawEventName);
792
1301
  }
793
1302
  }
794
1303
 
@@ -811,7 +1320,7 @@ if (parsed.isHook) {
811
1320
  runAmbientHookMode(parsed)
812
1321
  .then(() => process.exit(0))
813
1322
  .catch(() => {
814
- process.stdout.write("{}\n");
1323
+ writeDefaultHookOutput(Boolean(parsed.hookEvent), parsed.hookEvent);
815
1324
  process.exit(0);
816
1325
  });
817
1326
  return;
@@ -821,7 +1330,7 @@ const STANDARD_TOOLS = [
821
1330
  {
822
1331
  name: "add_memory",
823
1332
  description:
824
- "Store a persistent fact, architectural decision, user preference, or code snippet in `/ ml` Cloud.",
1333
+ "Explicitly store a memory in `/ ml` Cloud ONLY when the user directly asks you to call `add_memory`. Do NOT call `add_memory` proactively on normal user prompts, rules, or preferences — ambient lifecycle hooks automatically assimilate user rules, constraints, and state mutations in the background.",
825
1334
  inputSchema: {
826
1335
  type: "object",
827
1336
  properties: {
@@ -1235,6 +1744,10 @@ async function dispatchTool(opts, name, args = {}) {
1235
1744
  }
1236
1745
  if (name === "intervene_memory") {
1237
1746
  const rawText = String(args.text || args.prompt || "");
1747
+ const resolvedProjectId =
1748
+ args.project_id || args.projectId || process.env.SLASHML_PROJECT_ID || undefined;
1749
+ const resolvedSessionId =
1750
+ args.session_id || args.sessionId || process.env.SLASHML_SESSION_ID || undefined;
1238
1751
  return apiRequest(opts, "POST", "/v1/memory/intervene", {
1239
1752
  hook_event_name: args.hook_event_name || "UserPromptSubmit",
1240
1753
  prompt: args.prompt || rawText,
@@ -1244,6 +1757,8 @@ async function dispatchTool(opts, name, args = {}) {
1244
1757
  tool_response: args.tool_response || null,
1245
1758
  model: args.model || process.env.SLASHML_MODEL || undefined,
1246
1759
  user_id: uid,
1760
+ ...(resolvedProjectId ? { project_id: String(resolvedProjectId) } : {}),
1761
+ ...(resolvedSessionId ? { session_id: String(resolvedSessionId) } : {}),
1247
1762
  commit_writes: args.commit_writes !== undefined ? Boolean(args.commit_writes) : true,
1248
1763
  top_k: Number(args.top_k || args.limit || 5),
1249
1764
  });
@@ -1308,7 +1823,9 @@ rl.on("line", (line) => {
1308
1823
  ? CODE_MODE_TOOLS
1309
1824
  : parsed.codeOnly
1310
1825
  ? STANDARD_TOOLS.slice(4)
1311
- : STANDARD_TOOLS;
1826
+ : parsed.passiveWrites
1827
+ ? STANDARD_TOOLS.filter((t) => t.name !== "add_memory")
1828
+ : STANDARD_TOOLS;
1312
1829
  process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result: { tools } }) + "\n");
1313
1830
  return;
1314
1831
  }
package/dist/index.d.ts CHANGED
@@ -65,6 +65,12 @@ export interface InterveneOptions {
65
65
  hookEventName?: string;
66
66
  prompt?: string;
67
67
  text?: string;
68
+ last_assistant_message?: string | null;
69
+ lastAssistantMessage?: string | null;
70
+ stop_hook_active?: boolean;
71
+ stopHookActive?: boolean;
72
+ whispered_memory_ids?: string[] | null;
73
+ whisperedMemoryIds?: string[] | null;
68
74
  tool_name?: string | null;
69
75
  toolName?: string | null;
70
76
  tool_input?: Record<string, unknown> | null;
@@ -73,6 +79,10 @@ export interface InterveneOptions {
73
79
  toolResponse?: Record<string, unknown> | null;
74
80
  user_id?: string | null;
75
81
  userId?: string | null;
82
+ project_id?: string | null;
83
+ projectId?: string | null;
84
+ session_id?: string | null;
85
+ sessionId?: string | null;
76
86
  model?: string;
77
87
  commit_writes?: boolean;
78
88
  commitWrites?: boolean;
package/dist/index.js CHANGED
@@ -182,7 +182,7 @@ class MemoryClient {
182
182
  const headers = {
183
183
  Accept: "application/json",
184
184
  "Content-Type": "application/json",
185
- "User-Agent": "slashml-memory-ts/1.0.0",
185
+ "User-Agent": "slashml-memory-ts/1.0.6",
186
186
  };
187
187
  if (this.apiKey) {
188
188
  headers.Authorization = `Bearer ${this.apiKey}`;
@@ -277,15 +277,28 @@ class MemoryClient {
277
277
  : { ...(textOrPayload || {}), ...options };
278
278
  const resolvedText = opts.text ?? opts.prompt ?? "";
279
279
  const resolvedModel = opts.model ?? this.model;
280
+ const resolvedProjectId = opts.project_id ?? opts.projectId ?? this.projectId ?? null;
281
+ const resolvedSessionId = opts.session_id ?? opts.sessionId ?? null;
282
+ const lastAssistantMsg =
283
+ opts.last_assistant_message ?? opts.lastAssistantMessage ?? undefined;
284
+ const stopHookActive =
285
+ opts.stop_hook_active ?? opts.stopHookActive ?? undefined;
286
+ const whisperedIds =
287
+ opts.whispered_memory_ids ?? opts.whisperedMemoryIds ?? undefined;
280
288
  return this.request("POST", "/v1/memory/intervene", {
281
289
  jsonBody: {
282
290
  hook_event_name: opts.hook_event_name ?? opts.hookEventName ?? "UserPromptSubmit",
283
291
  prompt: opts.prompt ?? resolvedText,
284
292
  text: resolvedText,
293
+ ...(lastAssistantMsg !== undefined ? { last_assistant_message: lastAssistantMsg } : {}),
294
+ ...(stopHookActive !== undefined ? { stop_hook_active: Boolean(stopHookActive) } : {}),
295
+ ...(whisperedIds && whisperedIds.length > 0 ? { whispered_memory_ids: whisperedIds } : {}),
285
296
  tool_name: opts.tool_name ?? opts.toolName ?? null,
286
297
  tool_input: opts.tool_input ?? opts.toolInput ?? null,
287
298
  tool_response: opts.tool_response ?? opts.toolResponse ?? null,
288
299
  user_id: opts.user_id ?? opts.userId ?? "default",
300
+ ...(resolvedProjectId ? { project_id: resolvedProjectId } : {}),
301
+ ...(resolvedSessionId ? { session_id: resolvedSessionId } : {}),
289
302
  model: resolvedModel,
290
303
  commit_writes: opts.commit_writes ?? opts.commitWrites ?? true,
291
304
  top_k: opts.top_k ?? opts.topK ?? 5,
package/dist/index.mjs CHANGED
@@ -184,7 +184,7 @@ export class MemoryClient {
184
184
  const headers = {
185
185
  Accept: "application/json",
186
186
  "Content-Type": "application/json",
187
- "User-Agent": "slashml-memory-ts/1.0.0",
187
+ "User-Agent": "slashml-memory-ts/1.0.6",
188
188
  };
189
189
  if (this.apiKey) {
190
190
  headers.Authorization = `Bearer ${this.apiKey}`;
@@ -279,15 +279,28 @@ export class MemoryClient {
279
279
  : { ...(textOrPayload || {}), ...options };
280
280
  const resolvedText = opts.text ?? opts.prompt ?? "";
281
281
  const resolvedModel = opts.model ?? this.model;
282
+ const resolvedProjectId = opts.project_id ?? opts.projectId ?? this.projectId ?? null;
283
+ const resolvedSessionId = opts.session_id ?? opts.sessionId ?? null;
284
+ const lastAssistantMsg =
285
+ opts.last_assistant_message ?? opts.lastAssistantMessage ?? undefined;
286
+ const stopHookActive =
287
+ opts.stop_hook_active ?? opts.stopHookActive ?? undefined;
288
+ const whisperedIds =
289
+ opts.whispered_memory_ids ?? opts.whisperedMemoryIds ?? undefined;
282
290
  return this.request("POST", "/v1/memory/intervene", {
283
291
  jsonBody: {
284
292
  hook_event_name: opts.hook_event_name ?? opts.hookEventName ?? "UserPromptSubmit",
285
293
  prompt: opts.prompt ?? resolvedText,
286
294
  text: resolvedText,
295
+ ...(lastAssistantMsg !== undefined ? { last_assistant_message: lastAssistantMsg } : {}),
296
+ ...(stopHookActive !== undefined ? { stop_hook_active: Boolean(stopHookActive) } : {}),
297
+ ...(whisperedIds && whisperedIds.length > 0 ? { whispered_memory_ids: whisperedIds } : {}),
287
298
  tool_name: opts.tool_name ?? opts.toolName ?? null,
288
299
  tool_input: opts.tool_input ?? opts.toolInput ?? null,
289
300
  tool_response: opts.tool_response ?? opts.toolResponse ?? null,
290
301
  user_id: opts.user_id ?? opts.userId ?? "default",
302
+ ...(resolvedProjectId ? { project_id: resolvedProjectId } : {}),
303
+ ...(resolvedSessionId ? { session_id: resolvedSessionId } : {}),
291
304
  model: resolvedModel,
292
305
  commit_writes: opts.commit_writes ?? opts.commitWrites ?? true,
293
306
  top_k: opts.top_k ?? opts.topK ?? 5,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slashml/memory",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "/ ml (SlashML): Sub-Millisecond Stateful Agent & Code Memory SDK for TypeScript & Node.js",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://slashml.ai",
package/src/index.ts CHANGED
@@ -72,6 +72,12 @@ export interface InterveneOptions {
72
72
  hookEventName?: string;
73
73
  prompt?: string;
74
74
  text?: string;
75
+ last_assistant_message?: string | null;
76
+ lastAssistantMessage?: string | null;
77
+ stop_hook_active?: boolean;
78
+ stopHookActive?: boolean;
79
+ whispered_memory_ids?: string[] | null;
80
+ whisperedMemoryIds?: string[] | null;
75
81
  tool_name?: string | null;
76
82
  toolName?: string | null;
77
83
  tool_input?: Record<string, unknown> | null;
@@ -80,6 +86,10 @@ export interface InterveneOptions {
80
86
  toolResponse?: Record<string, unknown> | null;
81
87
  user_id?: string | null;
82
88
  userId?: string | null;
89
+ project_id?: string | null;
90
+ projectId?: string | null;
91
+ session_id?: string | null;
92
+ sessionId?: string | null;
83
93
  model?: string;
84
94
  commit_writes?: boolean;
85
95
  commitWrites?: boolean;
@@ -320,7 +330,7 @@ export class MemoryClient {
320
330
  const headers: Record<string, string> = {
321
331
  Accept: "application/json",
322
332
  "Content-Type": "application/json",
323
- "User-Agent": "slashml-memory-ts/1.0.0",
333
+ "User-Agent": "slashml-memory-ts/1.0.6",
324
334
  };
325
335
  if (this.apiKey) {
326
336
  headers.Authorization = `Bearer ${this.apiKey}`;
@@ -431,15 +441,28 @@ export class MemoryClient {
431
441
  : { ...textOrPayload, ...options };
432
442
  const resolvedText = opts.text ?? opts.prompt ?? "";
433
443
  const resolvedModel = opts.model ?? this.model;
444
+ const resolvedProjectId = opts.project_id ?? opts.projectId ?? this.projectId ?? null;
445
+ const resolvedSessionId = opts.session_id ?? opts.sessionId ?? null;
446
+ const lastAssistantMsg =
447
+ opts.last_assistant_message ?? opts.lastAssistantMessage ?? undefined;
448
+ const stopHookActive =
449
+ opts.stop_hook_active ?? opts.stopHookActive ?? undefined;
450
+ const whisperedIds =
451
+ opts.whispered_memory_ids ?? opts.whisperedMemoryIds ?? undefined;
434
452
  return this.request("POST", "/v1/memory/intervene", {
435
453
  jsonBody: {
436
454
  hook_event_name: opts.hook_event_name ?? opts.hookEventName ?? "UserPromptSubmit",
437
455
  prompt: opts.prompt ?? resolvedText,
438
456
  text: resolvedText,
457
+ ...(lastAssistantMsg !== undefined ? { last_assistant_message: lastAssistantMsg } : {}),
458
+ ...(stopHookActive !== undefined ? { stop_hook_active: Boolean(stopHookActive) } : {}),
459
+ ...(whisperedIds && whisperedIds.length > 0 ? { whispered_memory_ids: whisperedIds } : {}),
439
460
  tool_name: opts.tool_name ?? opts.toolName ?? null,
440
461
  tool_input: opts.tool_input ?? opts.toolInput ?? null,
441
462
  tool_response: opts.tool_response ?? opts.toolResponse ?? null,
442
463
  user_id: opts.user_id ?? opts.userId ?? "default",
464
+ ...(resolvedProjectId ? { project_id: resolvedProjectId } : {}),
465
+ ...(resolvedSessionId ? { session_id: resolvedSessionId } : {}),
443
466
  model: resolvedModel,
444
467
  commit_writes: opts.commit_writes ?? opts.commitWrites ?? true,
445
468
  top_k: opts.top_k ?? opts.topK ?? 5,