@slashml/memory 1.0.4 → 1.0.5

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.5";
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 Antigravity (agy) plugin hooks if ~/.gemini/config exists
531
+ const agyPluginDir = path.join(home, ".gemini", "config", "plugins", "slashml-memory");
532
+ if (fs.existsSync(path.join(home, ".gemini", "config")) || fs.existsSync(agyPluginDir)) {
533
+ fs.mkdirSync(agyPluginDir, { recursive: true });
534
+ const agyHooksPath = path.join(agyPluginDir, "hooks.json");
535
+ const agyHooks = {
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(agyHooksPath, JSON.stringify(agyHooks, null, 2) + "\n", "utf8");
578
+ console.log(`Configured / ml ambient lifecycle hooks in ${agyHooksPath}`);
579
+ }
478
580
  }
479
581
 
480
582
  function getTelemetryPath() {
@@ -648,6 +750,125 @@ 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 && entry.type === "PLANNER_RESPONSE" && typeof entry.content === "string" && entry.content.trim()) {
773
+ return entry.content.trim();
774
+ }
775
+ } catch {
776
+ // ignore partial line at start of buffer
777
+ }
778
+ }
779
+ } catch {
780
+ // ignore transcript read errors
781
+ }
782
+ return "";
783
+ }
784
+
785
+ function extractWhisperedContextFromCurrentTurn(transcriptPath) {
786
+ if (!transcriptPath || typeof transcriptPath !== "string") return { ids: [], blocks: [] };
787
+ const ids = new Set();
788
+ const blocks = new Set();
789
+ try {
790
+ if (!fs.existsSync(transcriptPath)) return { ids: [], blocks: [] };
791
+ const stat = fs.statSync(transcriptPath);
792
+ const maxBytes = 65536;
793
+ const start = Math.max(0, stat.size - maxBytes);
794
+ const len = stat.size - start;
795
+ if (len <= 0) return { ids: [], blocks: [] };
796
+ const fd = fs.openSync(transcriptPath, "r");
797
+ const buf = Buffer.alloc(len);
798
+ fs.readSync(fd, buf, 0, len, start);
799
+ fs.closeSync(fd);
800
+ const lines = buf.toString("utf8").split(/\r?\n/);
801
+ for (let i = lines.length - 1; i >= 0; i--) {
802
+ const line = lines[i].trim();
803
+ if (!line || !line.startsWith("{")) continue;
804
+ try {
805
+ const entry = JSON.parse(line);
806
+ if (!entry) continue;
807
+ if (entry.type === "USER_INPUT") break;
808
+ const content = typeof entry.content === "string" ? entry.content : "";
809
+ const memTagMatches = content.match(/<memory>[\s\S]*?<\/memory>/gi);
810
+ if (memTagMatches) {
811
+ for (const tag of memTagMatches) blocks.add(tag.trim());
812
+ }
813
+ if (
814
+ content.includes("<memory>") ||
815
+ content.includes("[MEMORY WHISPER]") ||
816
+ content.includes("[MEMORY INTERVENTION]") ||
817
+ content.includes("[MEMORY CONTEXT]")
818
+ ) {
819
+ const matches = content.match(/\bmem_[a-z0-9_]+\b/gi);
820
+ if (matches) {
821
+ for (const m of matches) ids.add(m);
822
+ }
823
+ }
824
+ } catch {
825
+ // ignore partial line at start of buffer
826
+ }
827
+ }
828
+ } catch {
829
+ // ignore transcript read errors
830
+ }
831
+ return { ids: Array.from(ids), blocks: Array.from(blocks) };
832
+ }
833
+
834
+ function writeDefaultHookOutput(isAntigravity, rawEventName) {
835
+ if (isAntigravity && rawEventName === "PreToolUse") {
836
+ process.stdout.write(JSON.stringify({ decision: "allow" }) + "\n");
837
+ } else {
838
+ process.stdout.write("{}\n");
839
+ }
840
+ }
841
+
842
+ function resolveHookProjectId(opts, payload) {
843
+ const explicit = [
844
+ payload && payload.project_id,
845
+ payload && payload.projectId,
846
+ process.env.SLASHML_PROJECT_ID,
847
+ ];
848
+ for (const val of explicit) {
849
+ if (typeof val === "string" && val.trim()) {
850
+ return val.trim();
851
+ }
852
+ }
853
+ const dirCandidates = [
854
+ opts && opts.repo,
855
+ payload && Array.isArray(payload.workspacePaths) && payload.workspacePaths[0],
856
+ payload && Array.isArray(payload.workspace_paths) && payload.workspace_paths[0],
857
+ payload && payload.cwd,
858
+ process.cwd(),
859
+ ];
860
+ for (const dir of dirCandidates) {
861
+ if (typeof dir === "string" && dir.trim()) {
862
+ const cleaned = dir.trim().replace(/[\\/]+$/, "");
863
+ const base = path.basename(cleaned);
864
+ if (base && base !== "." && base !== "/") {
865
+ return base;
866
+ }
867
+ }
868
+ }
869
+ return "";
870
+ }
871
+
651
872
  async function runAmbientHookMode(opts) {
652
873
  const crypto = require("crypto");
653
874
  const chunks = [];
@@ -655,8 +876,9 @@ async function runAmbientHookMode(opts) {
655
876
  chunks.push(Buffer.from(chunk));
656
877
  }
657
878
  const rawInput = Buffer.concat(chunks).toString("utf8").trim();
879
+ const cliEvent = opts.hookEvent ? String(opts.hookEvent).trim() : "";
658
880
  if (!rawInput) {
659
- process.stdout.write("{}\n");
881
+ writeDefaultHookOutput(Boolean(cliEvent), cliEvent);
660
882
  return;
661
883
  }
662
884
  const rawEventTokens = estimateTokens(rawInput);
@@ -664,98 +886,276 @@ async function runAmbientHookMode(opts) {
664
886
  try {
665
887
  payload = JSON.parse(rawInput);
666
888
  } catch {
667
- payload = { hook_event_name: "UserPromptSubmit", prompt: rawInput };
889
+ payload = { hook_event_name: cliEvent || "UserPromptSubmit", prompt: rawInput };
668
890
  }
669
891
 
670
- const hookEvent = String(
671
- payload.hook_event_name || payload.hook_event || payload.event || "UserPromptSubmit"
892
+ const isAntigravity = Boolean(
893
+ cliEvent === "PreInvocation" ||
894
+ payload.invocationNum !== undefined ||
895
+ payload.toolCall !== undefined ||
896
+ payload.terminationReason !== undefined ||
897
+ payload.workspacePaths !== undefined ||
898
+ payload.artifactDirectoryPath !== undefined ||
899
+ payload.conversationId !== undefined
672
900
  );
673
- const toolName = payload.tool_name ? String(payload.tool_name).trim() : null;
674
901
 
675
- // Skip read-only tools
902
+ let rawEventName = String(
903
+ cliEvent || payload.hook_event_name || payload.hook_event || payload.event || ""
904
+ ).trim();
905
+ if (!rawEventName) {
906
+ if (isAntigravity) {
907
+ if (payload.toolCall !== undefined) {
908
+ rawEventName =
909
+ payload.toolResponse !== undefined || payload.toolResult !== undefined
910
+ ? "PostToolUse"
911
+ : "PreToolUse";
912
+ } else if (payload.terminationReason !== undefined || payload.executionNum !== undefined) {
913
+ rawEventName = "Stop";
914
+ } else {
915
+ rawEventName = "PreInvocation";
916
+ }
917
+ } else {
918
+ rawEventName = "UserPromptSubmit";
919
+ }
920
+ }
921
+
922
+ const hookEvent = rawEventName === "PreInvocation" ? "UserPromptSubmit" : rawEventName;
923
+
924
+ // On Antigravity Stop, only evaluate normal completion turns (NO_TOOL_CALL)
925
+ if (isAntigravity && rawEventName === "Stop") {
926
+ if (payload.terminationReason && payload.terminationReason !== "NO_TOOL_CALL") {
927
+ writeDefaultHookOutput(isAntigravity, rawEventName);
928
+ return;
929
+ }
930
+ }
931
+
932
+ const toolCallObj =
933
+ payload.toolCall && typeof payload.toolCall === "object" ? payload.toolCall : null;
934
+ const toolName =
935
+ String(payload.tool_name || (toolCallObj && toolCallObj.name) || "").trim() || null;
936
+
937
+ const toolIn =
938
+ (payload.tool_input && typeof payload.tool_input === "object" ? payload.tool_input : null) ||
939
+ (toolCallObj && toolCallObj.args && typeof toolCallObj.args === "object"
940
+ ? toolCallObj.args
941
+ : null);
942
+
943
+ const dedupPath =
944
+ process.env.SLASHML_HOOK_STATE_PATH ||
945
+ path.join(os.homedir(), ".slashml", "hook_state.json");
946
+ let dedupState = { hashes: [] };
947
+ try {
948
+ if (fs.existsSync(dedupPath)) {
949
+ dedupState = JSON.parse(fs.readFileSync(dedupPath, "utf8")) || { hashes: [] };
950
+ }
951
+ } catch {
952
+ dedupState = { hashes: [] };
953
+ }
954
+ const sessionKey = String(
955
+ payload.conversationId ||
956
+ payload.session_id ||
957
+ payload.sessionId ||
958
+ process.env.SLASHML_SESSION_ID ||
959
+ ""
960
+ ).trim();
961
+ const projectId = resolveHookProjectId(opts, payload);
962
+ const scopeStateKey = `${projectId || "_default"}:${sessionKey || "_default"}`;
963
+
964
+ // / ml (SlashML · https://slashml.ai · github.com/slashml-ai/ml-memory · support@slashml.ai)
965
+ function persistPendingToolContext() {
966
+ if (!toolIn || typeof toolIn !== "object") return;
967
+ const refObj = {};
968
+ for (const k of ["file_path", "path", "Path", "command", "CommandLine"]) {
969
+ if (typeof toolIn[k] === "string" && toolIn[k].trim()) {
970
+ refObj[k] = toolIn[k].trim().slice(0, 400);
971
+ }
972
+ }
973
+ if (Object.keys(refObj).length === 0) return;
974
+ if (
975
+ !dedupState.pending_tool_input_by_session ||
976
+ typeof dedupState.pending_tool_input_by_session !== "object"
977
+ ) {
978
+ dedupState.pending_tool_input_by_session = {};
979
+ }
980
+ dedupState.pending_tool_input_by_session[scopeStateKey] = refObj;
981
+ try {
982
+ fs.mkdirSync(path.dirname(dedupPath), { recursive: true });
983
+ fs.writeFileSync(dedupPath, JSON.stringify(dedupState), "utf8");
984
+ } catch {
985
+ // ignore state persistence errors
986
+ }
987
+ }
988
+
989
+ // Skip read-only tools locally
676
990
  if ((hookEvent === "PreToolUse" || hookEvent === "PostToolUse") && toolName) {
677
991
  if (HOOK_READ_ONLY_TOOLS.has(toolName.toLowerCase())) {
992
+ persistPendingToolContext();
678
993
  recordLocalHookDrop(rawEventTokens);
679
- process.stdout.write("{}\n");
994
+ writeDefaultHookOutput(isAntigravity, rawEventName);
680
995
  return;
681
996
  }
682
997
  }
683
998
 
684
- const toolIn = payload.tool_input && typeof payload.tool_input === "object" ? payload.tool_input : null;
685
999
  const toolSummary = toolIn
686
- ? toolIn.command || toolIn.CommandLine || toolIn.new_string || toolIn.content || JSON.stringify(toolIn)
1000
+ ? toolIn.command ||
1001
+ toolIn.CommandLine ||
1002
+ toolIn.Replacement ||
1003
+ toolIn.new_string ||
1004
+ toolIn.Content ||
1005
+ toolIn.content ||
1006
+ JSON.stringify(toolIn)
687
1007
  : "";
688
- const deltaText = String(
689
- payload.prompt ||
690
- payload.text ||
691
- payload.user_prompt ||
1008
+
1009
+ if (
1010
+ (hookEvent === "PreToolUse" || hookEvent === "PostToolUse") &&
1011
+ toolName &&
1012
+ /^(bash|run_command|shell)$/i.test(toolName)
1013
+ ) {
1014
+ const cmdCheck = String(toolSummary || "")
1015
+ .trim()
1016
+ .toLowerCase()
1017
+ .replace(/^\s*cd\s+[^&;]+(?:&&|;)\s*/, "")
1018
+ .trim();
1019
+ const isReadOnlyCmd =
1020
+ /^(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(
1021
+ cmdCheck
1022
+ ) && !/[>]|(\brm\s|\bmv\s|\bcp\s|git\s+(push|commit)|\binstall\b)/.test(cmdCheck);
1023
+ if (isReadOnlyCmd) {
1024
+ persistPendingToolContext();
1025
+ recordLocalHookDrop(rawEventTokens);
1026
+ writeDefaultHookOutput(isAntigravity, rawEventName);
1027
+ return;
1028
+ }
1029
+ }
1030
+
1031
+ let rawCandidateText = "";
1032
+ if (hookEvent === "PreToolUse") {
1033
+ rawCandidateText = String(toolSummary || "");
1034
+ } else if (hookEvent === "PostToolUse") {
1035
+ const toolResp = payload.tool_response || payload.toolResponse || payload.toolResult;
1036
+ rawCandidateText = String(
1037
+ (toolResp ? (typeof toolResp === "string" ? toolResp : JSON.stringify(toolResp)) : "") ||
1038
+ toolSummary ||
1039
+ ""
1040
+ );
1041
+ } else if (hookEvent === "Stop") {
1042
+ rawCandidateText = String(
692
1043
  payload.last_assistant_message ||
693
- payload.assistant_message ||
694
- payload.response ||
695
- toolSummary ||
696
- (payload.tool_response ? JSON.stringify(payload.tool_response) : "")
697
- )
1044
+ payload.assistant_message ||
1045
+ payload.response ||
1046
+ extractLastPlannerResponseFromTranscript(payload.transcriptPath) ||
1047
+ ""
1048
+ );
1049
+ } else {
1050
+ rawCandidateText = String(
1051
+ payload.prompt || payload.user_prompt || payload.lastUserInput || payload.text || ""
1052
+ );
1053
+ }
1054
+
1055
+ const deltaText = rawCandidateText
698
1056
  .replace(/<thinking>[\s\S]*?<\/thinking>/gi, " ")
1057
+ .replace(/[\u2500-\u257f]+/g, " ")
699
1058
  .replace(/\s+/g, " ")
700
1059
  .trim()
701
1060
  .slice(0, 1024);
702
1061
 
703
- if (!deltaText || deltaText.length < 4 || /^(ok|okay|thanks|thank you|yes|no|sure|cool|lgtm)[.!]*$/i.test(deltaText)) {
1062
+ if (
1063
+ !deltaText ||
1064
+ deltaText.length < 4 ||
1065
+ /^(ok|okay|thanks|thank you|yes|no|sure|cool|lgtm)[.!]*$/i.test(deltaText)
1066
+ ) {
704
1067
  recordLocalHookDrop(rawEventTokens);
705
- process.stdout.write("{}\n");
1068
+ writeDefaultHookOutput(isAntigravity, rawEventName);
706
1069
  return;
707
1070
  }
708
1071
 
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
- }
1072
+ // Event deduplication (scoped to project/session/step and only persisted for non-actionable noise)
1073
+ const stepKey = String(
1074
+ payload.stepIdx ?? payload.invocationNum ?? payload.executionNum ?? ""
1075
+ );
721
1076
  const deltaHash = crypto
722
1077
  .createHash("sha1")
723
- .update(`${hookEvent}:${toolName || ""}:${deltaText.toLowerCase()}`)
1078
+ .update(
1079
+ `${projectId}:${sessionKey}:${stepKey}:${hookEvent}:${toolName || ""}:${deltaText.toLowerCase()}`
1080
+ )
724
1081
  .digest("hex")
725
1082
  .slice(0, 16);
726
1083
  if (Array.isArray(dedupState.hashes) && dedupState.hashes.includes(deltaHash)) {
727
1084
  recordLocalHookDrop(rawEventTokens);
728
- process.stdout.write("{}\n");
1085
+ writeDefaultHookOutput(isAntigravity, rawEventName);
729
1086
  return;
730
1087
  }
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
1088
 
739
1089
  if (!opts.apiKey) {
740
1090
  recordLocalHookDrop(rawEventTokens);
741
- process.stdout.write("{}\n");
1091
+ writeDefaultHookOutput(isAntigravity, rawEventName);
742
1092
  return;
743
1093
  }
744
1094
 
745
1095
  const telem = loadHookTelemetry();
746
1096
  const cleanTokens = estimateTokens(deltaText);
747
1097
  const strippedTokens = Math.max(0, rawEventTokens - cleanTokens);
1098
+ if (!dedupState.whispered_by_session || typeof dedupState.whispered_by_session !== "object") {
1099
+ dedupState.whispered_by_session = {};
1100
+ }
1101
+ if (!dedupState.whispered_blocks_by_session || typeof dedupState.whispered_blocks_by_session !== "object") {
1102
+ dedupState.whispered_blocks_by_session = {};
1103
+ }
1104
+ const isMidTurnContinuation =
1105
+ rawEventName === "PreInvocation" && Number(payload.invocationNum || 1) > 1;
1106
+ if (hookEvent === "UserPromptSubmit" && !isMidTurnContinuation && sessionKey) {
1107
+ dedupState.whispered_by_session[sessionKey] = [];
1108
+ dedupState.whispered_blocks_by_session[sessionKey] = [];
1109
+ }
1110
+ const transcriptWhispered = extractWhisperedContextFromCurrentTurn(payload.transcriptPath);
1111
+ const sessionWhispered =
1112
+ sessionKey && Array.isArray(dedupState.whispered_by_session[sessionKey])
1113
+ ? dedupState.whispered_by_session[sessionKey]
1114
+ : [];
1115
+ const sessionWhisperedBlocks =
1116
+ sessionKey && Array.isArray(dedupState.whispered_blocks_by_session[sessionKey])
1117
+ ? dedupState.whispered_blocks_by_session[sessionKey]
1118
+ : [];
1119
+ const whisperedMemoryIds = Array.from(new Set([...transcriptWhispered.ids, ...sessionWhispered]));
1120
+ const whisperedBlocks = Array.from(new Set([...transcriptWhispered.blocks, ...sessionWhisperedBlocks]));
1121
+ const streamTextForIntervene =
1122
+ (hookEvent === "Stop" || hookEvent === "PreToolUse") &&
1123
+ whisperedBlocks.length > 0 &&
1124
+ !deltaText.toLowerCase().includes("<memory>")
1125
+ ? `${whisperedBlocks.join("\n")}\n${deltaText}`
1126
+ : deltaText;
1127
+
1128
+ let effectiveToolIn = toolIn || null;
1129
+ if (
1130
+ !effectiveToolIn &&
1131
+ dedupState.pending_tool_input_by_session &&
1132
+ typeof dedupState.pending_tool_input_by_session === "object" &&
1133
+ dedupState.pending_tool_input_by_session[scopeStateKey]
1134
+ ) {
1135
+ effectiveToolIn = dedupState.pending_tool_input_by_session[scopeStateKey];
1136
+ delete dedupState.pending_tool_input_by_session[scopeStateKey];
1137
+ } else if (
1138
+ effectiveToolIn &&
1139
+ dedupState.pending_tool_input_by_session &&
1140
+ typeof dedupState.pending_tool_input_by_session === "object"
1141
+ ) {
1142
+ delete dedupState.pending_tool_input_by_session[scopeStateKey];
1143
+ }
748
1144
 
749
1145
  try {
750
1146
  const resp = await apiRequest(opts, "POST", "/v1/memory/intervene", {
751
1147
  hook_event_name: hookEvent,
752
- prompt: payload.prompt || deltaText,
753
- text: deltaText,
1148
+ prompt: payload.prompt || payload.lastUserInput || deltaText,
1149
+ text: streamTextForIntervene,
754
1150
  tool_name: toolName,
755
- tool_input: payload.tool_input || null,
756
- tool_response: payload.tool_response || null,
1151
+ tool_input: effectiveToolIn,
1152
+ tool_response: payload.tool_response || payload.toolResponse || null,
1153
+ whispered_memory_ids: whisperedMemoryIds,
1154
+ commit_writes: isMidTurnContinuation ? false : true,
757
1155
  model: process.env.SLASHML_MODEL || undefined,
758
1156
  user_id: opts.userId,
1157
+ ...(projectId ? { project_id: projectId } : {}),
1158
+ ...(sessionKey ? { session_id: sessionKey } : {}),
759
1159
  client_raw_tokens_delta: (telem.pending_raw_tokens_delta || 0) + strippedTokens,
760
1160
  client_dropped_tokens_delta: (telem.pending_dropped_tokens_delta || 0) + strippedTokens,
761
1161
  client_dropped_events_delta: telem.pending_dropped_events_delta || 0,
@@ -775,20 +1175,93 @@ async function runAmbientHookMode(opts) {
775
1175
  if (resp.write_novelty_action === "SUPERSEDES") {
776
1176
  telem.memories_superseded = (telem.memories_superseded || 0) + 1;
777
1177
  }
1178
+ dedupState.hashes = [];
778
1179
  }
779
1180
  if (resp.should_intervene) {
780
1181
  telem.amnesia_episodes_intercepted = (telem.amnesia_episodes_intercepted || 0) + 1;
1182
+ if (sessionKey && resp.triggered_memory_id) {
1183
+ const prev = Array.isArray(dedupState.whispered_by_session[sessionKey])
1184
+ ? dedupState.whispered_by_session[sessionKey]
1185
+ : [];
1186
+ if (!prev.includes(resp.triggered_memory_id)) {
1187
+ dedupState.whispered_by_session[sessionKey] = [...prev.slice(-15), resp.triggered_memory_id];
1188
+ }
1189
+ }
1190
+ if (sessionKey && resp.intervention_message) {
1191
+ const msgTags = String(resp.intervention_message).match(/<memory>[\s\S]*?<\/memory>/gi);
1192
+ if (msgTags) {
1193
+ const prevBlocks = Array.isArray(dedupState.whispered_blocks_by_session[sessionKey])
1194
+ ? dedupState.whispered_blocks_by_session[sessionKey]
1195
+ : [];
1196
+ const nextBlocks = Array.from(new Set([...prevBlocks, ...msgTags.map((t) => t.trim())]));
1197
+ dedupState.whispered_blocks_by_session[sessionKey] = nextBlocks.slice(-8);
1198
+ }
1199
+ }
781
1200
  }
782
1201
  } else {
783
1202
  telem.noise_tokens_filtered = (telem.noise_tokens_filtered || 0) + rawEventTokens;
784
1203
  telem.events_filtered_noise = (telem.events_filtered_noise || 0) + 1;
1204
+ dedupState.hashes = [
1205
+ ...(Array.isArray(dedupState.hashes) ? dedupState.hashes.slice(-63) : []),
1206
+ deltaHash,
1207
+ ];
1208
+ }
1209
+ try {
1210
+ fs.mkdirSync(path.dirname(dedupPath), { recursive: true });
1211
+ fs.writeFileSync(dedupPath, JSON.stringify(dedupState), "utf8");
1212
+ } catch {
1213
+ // ignore state persistence errors
785
1214
  }
786
1215
  saveHookTelemetry(telem);
787
- const out = resp && typeof resp.hook_output === "object" && resp.hook_output ? resp.hook_output : {};
1216
+
1217
+ let out = {};
1218
+ if (isAntigravity) {
1219
+ if (rawEventName === "PreInvocation") {
1220
+ if (resp && resp.should_intervene && resp.intervention_message) {
1221
+ out = {
1222
+ injectSteps: [
1223
+ {
1224
+ ephemeralMessage: resp.intervention_message,
1225
+ },
1226
+ ],
1227
+ };
1228
+ }
1229
+ } else if (rawEventName === "PreToolUse") {
1230
+ if (
1231
+ resp &&
1232
+ resp.should_intervene &&
1233
+ resp.intervention_severity === "BLOCK" &&
1234
+ resp.intervention_message
1235
+ ) {
1236
+ out = {
1237
+ decision: "deny",
1238
+ reason: resp.intervention_message,
1239
+ };
1240
+ } else {
1241
+ out = {
1242
+ decision: "allow",
1243
+ };
1244
+ }
1245
+ } else if (rawEventName === "Stop") {
1246
+ if (
1247
+ resp &&
1248
+ resp.should_intervene &&
1249
+ resp.intervention_severity === "BLOCK" &&
1250
+ resp.intervention_message
1251
+ ) {
1252
+ out = {
1253
+ decision: "continue",
1254
+ reason: resp.intervention_message,
1255
+ };
1256
+ }
1257
+ }
1258
+ } else {
1259
+ out = resp && typeof resp.hook_output === "object" && resp.hook_output ? resp.hook_output : {};
1260
+ }
788
1261
  process.stdout.write(JSON.stringify(out) + "\n");
789
1262
  } catch {
790
1263
  // Fail-open on network errors so the IDE is never blocked
791
- process.stdout.write("{}\n");
1264
+ writeDefaultHookOutput(isAntigravity, rawEventName);
792
1265
  }
793
1266
  }
794
1267
 
@@ -811,7 +1284,7 @@ if (parsed.isHook) {
811
1284
  runAmbientHookMode(parsed)
812
1285
  .then(() => process.exit(0))
813
1286
  .catch(() => {
814
- process.stdout.write("{}\n");
1287
+ writeDefaultHookOutput(Boolean(parsed.hookEvent), parsed.hookEvent);
815
1288
  process.exit(0);
816
1289
  });
817
1290
  return;
@@ -821,7 +1294,7 @@ const STANDARD_TOOLS = [
821
1294
  {
822
1295
  name: "add_memory",
823
1296
  description:
824
- "Store a persistent fact, architectural decision, user preference, or code snippet in `/ ml` Cloud.",
1297
+ "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
1298
  inputSchema: {
826
1299
  type: "object",
827
1300
  properties: {
@@ -1235,6 +1708,10 @@ async function dispatchTool(opts, name, args = {}) {
1235
1708
  }
1236
1709
  if (name === "intervene_memory") {
1237
1710
  const rawText = String(args.text || args.prompt || "");
1711
+ const resolvedProjectId =
1712
+ args.project_id || args.projectId || process.env.SLASHML_PROJECT_ID || undefined;
1713
+ const resolvedSessionId =
1714
+ args.session_id || args.sessionId || process.env.SLASHML_SESSION_ID || undefined;
1238
1715
  return apiRequest(opts, "POST", "/v1/memory/intervene", {
1239
1716
  hook_event_name: args.hook_event_name || "UserPromptSubmit",
1240
1717
  prompt: args.prompt || rawText,
@@ -1244,6 +1721,8 @@ async function dispatchTool(opts, name, args = {}) {
1244
1721
  tool_response: args.tool_response || null,
1245
1722
  model: args.model || process.env.SLASHML_MODEL || undefined,
1246
1723
  user_id: uid,
1724
+ ...(resolvedProjectId ? { project_id: String(resolvedProjectId) } : {}),
1725
+ ...(resolvedSessionId ? { session_id: String(resolvedSessionId) } : {}),
1247
1726
  commit_writes: args.commit_writes !== undefined ? Boolean(args.commit_writes) : true,
1248
1727
  top_k: Number(args.top_k || args.limit || 5),
1249
1728
  });
@@ -1308,7 +1787,9 @@ rl.on("line", (line) => {
1308
1787
  ? CODE_MODE_TOOLS
1309
1788
  : parsed.codeOnly
1310
1789
  ? STANDARD_TOOLS.slice(4)
1311
- : STANDARD_TOOLS;
1790
+ : parsed.passiveWrites
1791
+ ? STANDARD_TOOLS.filter((t) => t.name !== "add_memory")
1792
+ : STANDARD_TOOLS;
1312
1793
  process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result: { tools } }) + "\n");
1313
1794
  return;
1314
1795
  }
package/dist/index.d.ts CHANGED
@@ -73,6 +73,10 @@ export interface InterveneOptions {
73
73
  toolResponse?: Record<string, unknown> | null;
74
74
  user_id?: string | null;
75
75
  userId?: string | null;
76
+ project_id?: string | null;
77
+ projectId?: string | null;
78
+ session_id?: string | null;
79
+ sessionId?: string | null;
76
80
  model?: string;
77
81
  commit_writes?: boolean;
78
82
  commitWrites?: boolean;
package/dist/index.js CHANGED
@@ -277,6 +277,8 @@ 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;
280
282
  return this.request("POST", "/v1/memory/intervene", {
281
283
  jsonBody: {
282
284
  hook_event_name: opts.hook_event_name ?? opts.hookEventName ?? "UserPromptSubmit",
@@ -286,6 +288,8 @@ class MemoryClient {
286
288
  tool_input: opts.tool_input ?? opts.toolInput ?? null,
287
289
  tool_response: opts.tool_response ?? opts.toolResponse ?? null,
288
290
  user_id: opts.user_id ?? opts.userId ?? "default",
291
+ ...(resolvedProjectId ? { project_id: resolvedProjectId } : {}),
292
+ ...(resolvedSessionId ? { session_id: resolvedSessionId } : {}),
289
293
  model: resolvedModel,
290
294
  commit_writes: opts.commit_writes ?? opts.commitWrites ?? true,
291
295
  top_k: opts.top_k ?? opts.topK ?? 5,
package/dist/index.mjs CHANGED
@@ -279,6 +279,8 @@ 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;
282
284
  return this.request("POST", "/v1/memory/intervene", {
283
285
  jsonBody: {
284
286
  hook_event_name: opts.hook_event_name ?? opts.hookEventName ?? "UserPromptSubmit",
@@ -288,6 +290,8 @@ export class MemoryClient {
288
290
  tool_input: opts.tool_input ?? opts.toolInput ?? null,
289
291
  tool_response: opts.tool_response ?? opts.toolResponse ?? null,
290
292
  user_id: opts.user_id ?? opts.userId ?? "default",
293
+ ...(resolvedProjectId ? { project_id: resolvedProjectId } : {}),
294
+ ...(resolvedSessionId ? { session_id: resolvedSessionId } : {}),
291
295
  model: resolvedModel,
292
296
  commit_writes: opts.commit_writes ?? opts.commitWrites ?? true,
293
297
  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.5",
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
@@ -80,6 +80,10 @@ export interface InterveneOptions {
80
80
  toolResponse?: Record<string, unknown> | null;
81
81
  user_id?: string | null;
82
82
  userId?: string | null;
83
+ project_id?: string | null;
84
+ projectId?: string | null;
85
+ session_id?: string | null;
86
+ sessionId?: string | null;
83
87
  model?: string;
84
88
  commit_writes?: boolean;
85
89
  commitWrites?: boolean;
@@ -431,6 +435,8 @@ export class MemoryClient {
431
435
  : { ...textOrPayload, ...options };
432
436
  const resolvedText = opts.text ?? opts.prompt ?? "";
433
437
  const resolvedModel = opts.model ?? this.model;
438
+ const resolvedProjectId = opts.project_id ?? opts.projectId ?? this.projectId ?? null;
439
+ const resolvedSessionId = opts.session_id ?? opts.sessionId ?? null;
434
440
  return this.request("POST", "/v1/memory/intervene", {
435
441
  jsonBody: {
436
442
  hook_event_name: opts.hook_event_name ?? opts.hookEventName ?? "UserPromptSubmit",
@@ -440,6 +446,8 @@ export class MemoryClient {
440
446
  tool_input: opts.tool_input ?? opts.toolInput ?? null,
441
447
  tool_response: opts.tool_response ?? opts.toolResponse ?? null,
442
448
  user_id: opts.user_id ?? opts.userId ?? "default",
449
+ ...(resolvedProjectId ? { project_id: resolvedProjectId } : {}),
450
+ ...(resolvedSessionId ? { session_id: resolvedSessionId } : {}),
443
451
  model: resolvedModel,
444
452
  commit_writes: opts.commit_writes ?? opts.commitWrites ?? true,
445
453
  top_k: opts.top_k ?? opts.topK ?? 5,