@slashml/memory 1.0.13 → 1.0.15

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.13";
13
+ const PACKAGE_VERSION = "1.0.15";
14
14
  const MAX_STOP_BLOCKS_PER_PROMPT = 3;
15
15
 
16
16
  function printHelp() {
@@ -31,6 +31,9 @@ Options:
31
31
  --api-key <key> SlashML API key (or set SLASHML_API_KEY env var)
32
32
  --workspace, --repo <path> Optional workspace directory to scope/index (defaults to process.cwd() at runtime)
33
33
  --user-id <id> Default user/workspace namespace (default: SLASHML_USER_ID or "default")
34
+ --agent-id <id> Caller agent identity for per-agent access & redaction policies (or SLASHML_AGENT_ID)
35
+ --redact-policy <policy> Default redaction preset or comma-separated buckets (or SLASHML_REDACT_POLICY)
36
+ --redact-scope <scope> Default redaction scope: memorize_and_recall | recall_only (or SLASHML_REDACT_SCOPE)
34
37
  --code-only Expose only code & bug-localization MCP tools
35
38
  --code-mode Expose compact single meta-tool (execute_memory_code)
36
39
  --init Write ml-memory MCP entry to Cursor, Windsurf, or .mcp.json
@@ -183,6 +186,9 @@ function parseCliArgs(argv) {
183
186
  let baseUrl = (process.env.SLASHML_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
184
187
  let consoleUrl = (process.env.SLASHML_CONSOLE_URL || DEFAULT_CONSOLE_URL).replace(/\/+$/, "");
185
188
  let userId = process.env.SLASHML_USER_ID || "default";
189
+ let agentId = (process.env.SLASHML_AGENT_ID || "").trim() || null;
190
+ let redactPolicy = (process.env.SLASHML_REDACT_POLICY || "").trim() || null;
191
+ let redactScope = (process.env.SLASHML_REDACT_SCOPE || "").trim() || null;
186
192
  let codeOnly = false;
187
193
  let codeMode = false;
188
194
  let passiveWrites = process.env.SLASHML_PASSIVE_WRITES === "1";
@@ -192,6 +198,7 @@ function parseCliArgs(argv) {
192
198
  let verifyCode = null;
193
199
  let writeEnv = false;
194
200
  let isHook = false;
201
+ let isHookDaemon = false;
195
202
  let hookEvent = null;
196
203
  let isInstallHooks = false;
197
204
  let isStatus = false;
@@ -221,6 +228,8 @@ function parseCliArgs(argv) {
221
228
  isInit = true;
222
229
  } else if (arg === "--hook" || arg === "hook") {
223
230
  isHook = true;
231
+ } else if (arg === "--hook-daemon") {
232
+ isHookDaemon = true;
224
233
  } else if (arg === "--hook-event" && i + 1 < argv.length) {
225
234
  hookEvent = argv[++i];
226
235
  } else if (arg === "--install-hooks" || arg === "install-hooks") {
@@ -269,6 +278,12 @@ function parseCliArgs(argv) {
269
278
  consoleUrl = argv[++i].replace(/\/+$/, "");
270
279
  } else if (arg === "--user-id" && i + 1 < argv.length) {
271
280
  userId = argv[++i];
281
+ } else if (arg === "--agent-id" && i + 1 < argv.length) {
282
+ agentId = argv[++i].trim() || null;
283
+ } else if (arg === "--redact-policy" && i + 1 < argv.length) {
284
+ redactPolicy = argv[++i].trim() || null;
285
+ } else if (arg === "--redact-scope" && i + 1 < argv.length) {
286
+ redactScope = argv[++i].trim() || null;
272
287
  } else if ((arg === "--repo" || arg === "--workspace") && i + 1 < argv.length) {
273
288
  repo = argv[++i];
274
289
  } else if (arg === "--signup" && i + 1 < argv.length) {
@@ -302,6 +317,9 @@ function parseCliArgs(argv) {
302
317
  baseUrl,
303
318
  consoleUrl,
304
319
  userId,
320
+ agentId,
321
+ redactPolicy,
322
+ redactScope,
305
323
  codeOnly,
306
324
  codeMode,
307
325
  passiveWrites,
@@ -311,6 +329,7 @@ function parseCliArgs(argv) {
311
329
  verifyCode,
312
330
  writeEnv,
313
331
  isHook,
332
+ isHookDaemon,
314
333
  hookEvent,
315
334
  isInstallHooks,
316
335
  isStatus,
@@ -366,7 +385,7 @@ function saveApiKeyToEnvFile(apiKey, cwd = process.cwd()) {
366
385
 
367
386
  const GENERIC_SKILL_NAMES = new Set(["ml-memory", "/ml-memory", "slashml", "all", "default"]);
368
387
 
369
- function nativeNodeInit(skill, apiKey, repo = null, writeEnv = false) {
388
+ function nativeNodeInit(skill, apiKey, repo = null, writeEnv = false, extraEnv = {}) {
370
389
  const home = os.homedir();
371
390
  const cwd = process.cwd();
372
391
  const targets = [
@@ -398,10 +417,21 @@ function nativeNodeInit(skill, apiKey, repo = null, writeEnv = false) {
398
417
  args,
399
418
  };
400
419
  const resolvedKey = apiKey || process.env.SLASHML_API_KEY;
420
+ const envMap = {};
401
421
  if (resolvedKey) {
402
- serverEntry.env = {
403
- SLASHML_API_KEY: resolvedKey,
404
- };
422
+ envMap.SLASHML_API_KEY = resolvedKey;
423
+ }
424
+ if (extraEnv.agentId) {
425
+ envMap.SLASHML_AGENT_ID = extraEnv.agentId;
426
+ }
427
+ if (extraEnv.redactPolicy) {
428
+ envMap.SLASHML_REDACT_POLICY = extraEnv.redactPolicy;
429
+ }
430
+ if (extraEnv.redactScope) {
431
+ envMap.SLASHML_REDACT_SCOPE = extraEnv.redactScope;
432
+ }
433
+ if (Object.keys(envMap).length > 0) {
434
+ serverEntry.env = envMap;
405
435
  }
406
436
  if (writeEnv && resolvedKey) {
407
437
  saveApiKeyToEnvFile(resolvedKey, cwd);
@@ -498,7 +528,11 @@ async function runCliVerify(email, code, parsedArgs) {
498
528
  envSavedPath = path.join(process.cwd(), ".env");
499
529
  }
500
530
  if (parsedArgs.isInit) {
501
- nativeNodeInit(parsedArgs.skill, provisionedKey, parsedArgs.repo, false);
531
+ nativeNodeInit(parsedArgs.skill, provisionedKey, parsedArgs.repo, false, {
532
+ agentId: parsedArgs.agentId,
533
+ redactPolicy: parsedArgs.redactPolicy,
534
+ redactScope: parsedArgs.redactScope,
535
+ });
502
536
  }
503
537
  console.log(
504
538
  JSON.stringify({
@@ -544,7 +578,11 @@ if (parsed.verifyEmail) {
544
578
  }
545
579
 
546
580
  if (parsed.isInit) {
547
- nativeNodeInit(parsed.skill, parsed.apiKey, parsed.repo, parsed.writeEnv);
581
+ nativeNodeInit(parsed.skill, parsed.apiKey, parsed.repo, parsed.writeEnv, {
582
+ agentId: parsed.agentId,
583
+ redactPolicy: parsed.redactPolicy,
584
+ redactScope: parsed.redactScope,
585
+ });
548
586
  if (process.env.SLASHML_DISABLE_AUTO_HOOKS !== "1") {
549
587
  try {
550
588
  installAmbientHooks(parsed.apiKey, { quiet: false, onlyIfDirExists: false });
@@ -625,11 +663,64 @@ function upsertSlashmlRuleBlock(filePath, bodyText = AMBIENT_RULE_MARKDOWN) {
625
663
  return true;
626
664
  }
627
665
 
666
+ function quoteHookShellArg(p) {
667
+ const s = String(p || "");
668
+ return /\s/.test(s) ? `"${s.replace(/"/g, '\\"')}"` : s;
669
+ }
670
+
671
+ function ensureHookLauncherInstalled(home) {
672
+ const launcherPath = path.join(home, ".slashml", "bin", "slashml-hook.js");
673
+ try {
674
+ fs.mkdirSync(path.dirname(launcherPath), { recursive: true });
675
+ const src = fs.readFileSync(__filename);
676
+ let needsWrite = true;
677
+ if (fs.existsSync(launcherPath)) {
678
+ try {
679
+ const existing = fs.readFileSync(launcherPath);
680
+ if (Buffer.compare(src, existing) === 0) {
681
+ needsWrite = false;
682
+ }
683
+ } catch {
684
+ needsWrite = true;
685
+ }
686
+ }
687
+ if (needsWrite) {
688
+ const tmpPath = `${launcherPath}.${process.pid}.tmp`;
689
+ fs.writeFileSync(tmpPath, src, { mode: 0o755 });
690
+ fs.chmodSync(tmpPath, 0o755);
691
+ fs.renameSync(tmpPath, launcherPath);
692
+ }
693
+ const nodeBin =
694
+ process.execPath && fs.existsSync(process.execPath) ? process.execPath : "node";
695
+ return {
696
+ nodeBin,
697
+ launcherPath,
698
+ hookCmd: `${quoteHookShellArg(nodeBin)} ${quoteHookShellArg(launcherPath)} --hook`,
699
+ };
700
+ } catch {
701
+ return {
702
+ nodeBin: "node",
703
+ launcherPath: __filename,
704
+ hookCmd: `${quoteHookShellArg(process.execPath || "node")} ${quoteHookShellArg(__filename)} --hook`,
705
+ };
706
+ }
707
+ }
708
+
709
+ function isSlashmlHookCommand(cmd) {
710
+ if (typeof cmd !== "string") return false;
711
+ return (
712
+ cmd.includes("@slashml/") ||
713
+ cmd.includes("slashml-mcp") ||
714
+ cmd.includes("slashml-hook.js") ||
715
+ cmd.includes("slashml.mcp_server")
716
+ );
717
+ }
718
+
628
719
  function installAmbientHooks(apiKey, opts = {}) {
629
720
  const quiet = Boolean(opts && opts.quiet);
630
721
  const onlyIfDirExists = Boolean(opts && opts.onlyIfDirExists);
631
722
  const home = os.homedir();
632
- const hookCmd = "npx -y @slashml/memory --hook";
723
+ const { nodeBin, launcherPath, hookCmd } = ensureHookLauncherInstalled(home);
633
724
 
634
725
  // 1. Claude Code (~/.claude/settings.json + ~/.claude/CLAUDE.md)
635
726
  const claudeDir = path.join(home, ".claude");
@@ -649,14 +740,32 @@ function installAmbientHooks(apiKey, opts = {}) {
649
740
  }
650
741
  let changed = false;
651
742
  for (const eventName of ["UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"]) {
743
+ const targetEventCmd = `${hookCmd} --hook-event ${eventName}`;
652
744
  if (!quiet || !Array.isArray(settings.hooks[eventName]) || settings.hooks[eventName].length === 0) {
653
745
  settings.hooks[eventName] = [
654
746
  {
655
747
  matcher: ".*",
656
- hooks: [{ type: "command", command: hookCmd, timeout: 10 }],
748
+ hooks: [{ type: "command", command: targetEventCmd, timeout: 30 }],
657
749
  },
658
750
  ];
659
751
  changed = true;
752
+ } else {
753
+ for (const group of settings.hooks[eventName]) {
754
+ if (group && Array.isArray(group.hooks)) {
755
+ for (const h of group.hooks) {
756
+ if (h && isSlashmlHookCommand(h.command)) {
757
+ if (typeof h.timeout !== "number" || h.timeout < 30) {
758
+ h.timeout = 30;
759
+ changed = true;
760
+ }
761
+ if (h.command.trim().startsWith("npx ")) {
762
+ h.command = targetEventCmd;
763
+ changed = true;
764
+ }
765
+ }
766
+ }
767
+ }
768
+ }
660
769
  }
661
770
  }
662
771
  if (apiKey && (!quiet || !settings.env || !settings.env.SLASHML_API_KEY)) {
@@ -747,30 +856,61 @@ function installAmbientHooks(apiKey, opts = {}) {
747
856
  UserPromptSubmit: [
748
857
  {
749
858
  matcher: ".*",
750
- hooks: [{ type: "command", command: `${hookCmd} --hook-event UserPromptSubmit`, timeout: 10 }],
859
+ hooks: [{ type: "command", command: `${hookCmd} --hook-event UserPromptSubmit`, timeout: 30 }],
751
860
  },
752
861
  ],
753
862
  PreToolUse: [
754
863
  {
755
864
  matcher: ".*",
756
- hooks: [{ type: "command", command: `${hookCmd} --hook-event PreToolUse`, timeout: 10 }],
865
+ hooks: [{ type: "command", command: `${hookCmd} --hook-event PreToolUse`, timeout: 30 }],
757
866
  },
758
867
  ],
759
868
  PostToolUse: [
760
869
  {
761
870
  matcher: ".*",
762
- hooks: [{ type: "command", command: `${hookCmd} --hook-event PostToolUse`, timeout: 10 }],
871
+ hooks: [{ type: "command", command: `${hookCmd} --hook-event PostToolUse`, timeout: 30 }],
763
872
  },
764
873
  ],
765
874
  Stop: [
766
875
  {
767
876
  matcher: ".*",
768
- hooks: [{ type: "command", command: `${hookCmd} --hook-event Stop`, timeout: 10 }],
877
+ hooks: [{ type: "command", command: `${hookCmd} --hook-event Stop`, timeout: 30 }],
769
878
  },
770
879
  ],
771
880
  },
772
881
  };
773
882
  fs.writeFileSync(codexHooksPath, JSON.stringify(codexHooks, null, 2) + "\n", "utf8");
883
+ } else {
884
+ try {
885
+ const codexCfg = JSON.parse(fs.readFileSync(codexHooksPath, "utf8"));
886
+ let codexChanged = false;
887
+ if (codexCfg && codexCfg.hooks && typeof codexCfg.hooks === "object") {
888
+ for (const eventName of ["UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"]) {
889
+ const groups = codexCfg.hooks[eventName];
890
+ if (!Array.isArray(groups)) continue;
891
+ for (const group of groups) {
892
+ if (!group || !Array.isArray(group.hooks)) continue;
893
+ for (const h of group.hooks) {
894
+ if (h && isSlashmlHookCommand(h.command)) {
895
+ if (typeof h.timeout !== "number" || h.timeout < 30) {
896
+ h.timeout = 30;
897
+ codexChanged = true;
898
+ }
899
+ if (h.command.trim().startsWith("npx ")) {
900
+ h.command = `${hookCmd} --hook-event ${eventName}`;
901
+ codexChanged = true;
902
+ }
903
+ }
904
+ }
905
+ }
906
+ }
907
+ }
908
+ if (codexChanged) {
909
+ fs.writeFileSync(codexHooksPath, JSON.stringify(codexCfg, null, 2) + "\n", "utf8");
910
+ }
911
+ } catch {
912
+ // ignore malformed codex hooks.json
913
+ }
774
914
  }
775
915
  try {
776
916
  upsertSlashmlRuleBlock(path.join(codexDir, "AGENTS.md"));
@@ -782,7 +922,7 @@ function installAmbientHooks(apiKey, opts = {}) {
782
922
  }
783
923
  }
784
924
 
785
- // 5. Gemini CLI & Antigravity (~/.gemini/config/plugins/slashml-memory + ~/.gemini/GEMINI.md)
925
+ // 5. Gemini CLI (~/.gemini/config/plugins/slashml-memory + ~/.gemini/GEMINI.md)
786
926
  const geminiConfigDir = path.join(home, ".gemini", "config");
787
927
  const geminiPluginsRoot = path.join(geminiConfigDir, "plugins");
788
928
  let geminiPluginDir = path.join(geminiPluginsRoot, "slashml-memory");
@@ -816,7 +956,7 @@ function installAmbientHooks(apiKey, opts = {}) {
816
956
  {
817
957
  type: "command",
818
958
  command: `${hookCmd} --hook-event PreInvocation`,
819
- timeout: 10,
959
+ timeout: 30,
820
960
  },
821
961
  ],
822
962
  PreToolUse: [
@@ -826,7 +966,7 @@ function installAmbientHooks(apiKey, opts = {}) {
826
966
  {
827
967
  type: "command",
828
968
  command: `${hookCmd} --hook-event PreToolUse`,
829
- timeout: 10,
969
+ timeout: 30,
830
970
  },
831
971
  ],
832
972
  },
@@ -838,7 +978,7 @@ function installAmbientHooks(apiKey, opts = {}) {
838
978
  {
839
979
  type: "command",
840
980
  command: `${hookCmd} --hook-event PostToolUse`,
841
- timeout: 10,
981
+ timeout: 30,
842
982
  },
843
983
  ],
844
984
  },
@@ -847,12 +987,45 @@ function installAmbientHooks(apiKey, opts = {}) {
847
987
  {
848
988
  type: "command",
849
989
  command: `${hookCmd} --hook-event Stop`,
850
- timeout: 10,
990
+ timeout: 30,
851
991
  },
852
992
  ],
853
993
  },
854
994
  };
855
995
  fs.writeFileSync(geminiHooksPath, JSON.stringify(geminiHooks, null, 2) + "\n", "utf8");
996
+ } else {
997
+ try {
998
+ const gemCfg = JSON.parse(fs.readFileSync(geminiHooksPath, "utf8"));
999
+ const rootObj = gemCfg && gemCfg["slashml-ambient-memory"];
1000
+ let gemChanged = false;
1001
+ if (rootObj && typeof rootObj === "object") {
1002
+ for (const eventName of ["PreInvocation", "PreToolUse", "PostToolUse", "Stop"]) {
1003
+ const entries = rootObj[eventName];
1004
+ if (!Array.isArray(entries)) continue;
1005
+ for (const item of entries) {
1006
+ if (!item || typeof item !== "object") continue;
1007
+ const leafList = Array.isArray(item.hooks) ? item.hooks : [item];
1008
+ for (const h of leafList) {
1009
+ if (h && isSlashmlHookCommand(h.command)) {
1010
+ if (typeof h.timeout !== "number" || h.timeout < 30) {
1011
+ h.timeout = 30;
1012
+ gemChanged = true;
1013
+ }
1014
+ if (h.command.trim().startsWith("npx ")) {
1015
+ h.command = `${hookCmd} --hook-event ${eventName}`;
1016
+ gemChanged = true;
1017
+ }
1018
+ }
1019
+ }
1020
+ }
1021
+ }
1022
+ }
1023
+ if (gemChanged) {
1024
+ fs.writeFileSync(geminiHooksPath, JSON.stringify(gemCfg, null, 2) + "\n", "utf8");
1025
+ }
1026
+ } catch {
1027
+ // ignore malformed gemini hooks.json
1028
+ }
856
1029
  }
857
1030
  const geminiPluginJsonPath = path.join(geminiPluginDir, "plugin.json");
858
1031
  if (!fs.existsSync(geminiPluginJsonPath)) {
@@ -888,10 +1061,10 @@ function installAmbientHooks(apiKey, opts = {}) {
888
1061
 
889
1062
  function runHook(event, payload) {
890
1063
  try {
891
- const res = spawnSync("npx", ["-y", "@slashml/memory", "--hook", "--hook-event", event], {
1064
+ const res = spawnSync(${JSON.stringify(nodeBin)}, [${JSON.stringify(launcherPath)}, "--hook", "--hook-event", event], {
892
1065
  input: JSON.stringify({ hook_event_name: event, ...payload }),
893
1066
  encoding: "utf8",
894
- timeout: 8000,
1067
+ timeout: 30000,
895
1068
  });
896
1069
  if (res.stdout && res.stdout.trim().startsWith("{")) {
897
1070
  return JSON.parse(res.stdout.trim());
@@ -984,7 +1157,7 @@ export default SlashMLMemoryPlugin;
984
1157
  const hooksDir = path.join(hermesDir, "agent-hooks");
985
1158
  fs.mkdirSync(hooksDir, { recursive: true });
986
1159
  const scriptPath = path.join(hooksDir, "slashml-hook.sh");
987
- const scriptBody = `#!/usr/bin/env bash\nexec npx -y @slashml/memory --hook --hook-event "\${1:-pre_tool_call}"\n`;
1160
+ const scriptBody = `#!/usr/bin/env bash\nexec ${hookCmd} --hook-event "\${1:-pre_tool_call}"\n`;
988
1161
  if (!quiet || !fs.existsSync(scriptPath)) {
989
1162
  fs.writeFileSync(scriptPath, scriptBody, { encoding: "utf8", mode: 0o755 });
990
1163
  fs.chmodSync(scriptPath, 0o755);
@@ -1028,16 +1201,16 @@ export default SlashMLMemoryPlugin;
1028
1201
  "hooks:",
1029
1202
  ` pre_llm_call:`,
1030
1203
  ` - command: "${scriptPath} pre_llm_call"`,
1031
- ` timeout: 10`,
1204
+ ` timeout: 30`,
1032
1205
  ` pre_tool_call:`,
1033
1206
  ` - command: "${scriptPath} pre_tool_call"`,
1034
- ` timeout: 10`,
1207
+ ` timeout: 30`,
1035
1208
  ` post_tool_call:`,
1036
1209
  ` - command: "${scriptPath} post_tool_call"`,
1037
- ` timeout: 10`,
1210
+ ` timeout: 30`,
1038
1211
  ` post_llm_call:`,
1039
1212
  ` - command: "${scriptPath} post_llm_call"`,
1040
- ` timeout: 10`,
1213
+ ` timeout: 30`,
1041
1214
  ].join("\n");
1042
1215
  yamlText = yamlText.trim() ? `${yamlText.replace(/\n*$/, "")}\n\n${hooksBlock}\n` : `${hooksBlock}\n`;
1043
1216
  fs.writeFileSync(configYamlPath, yamlText, "utf8");
@@ -1359,6 +1532,11 @@ function extractWhisperedContextFromCurrentTurn(transcriptPath) {
1359
1532
  if (matches) {
1360
1533
  for (const m of matches) ids.add(m);
1361
1534
  }
1535
+ const ruleHeaderRe = /\[MEMORY (?:INTERVENTION|WHISPER|CONTEXT)\]:\s*\(([^,\s)]+)/gi;
1536
+ let rm;
1537
+ while ((rm = ruleHeaderRe.exec(content)) !== null) {
1538
+ if (rm[1]) ids.add(rm[1].trim());
1539
+ }
1362
1540
  }
1363
1541
  } catch {
1364
1542
  // ignore partial line at start of buffer
@@ -1531,7 +1709,6 @@ async function runAmbientHookMode(opts) {
1531
1709
  }
1532
1710
  }
1533
1711
 
1534
- // Enforce hard 3-retry safety ceiling locally if harness passes an explicit loop_count >= 3
1535
1712
  if (hookEvent === "Stop" && Number(payload.loop_count || 0) >= MAX_STOP_BLOCKS_PER_PROMPT) {
1536
1713
  writeDefaultHookOutput(isGeminiHook, rawEventName, isCursorHook);
1537
1714
  return;
@@ -1668,6 +1845,8 @@ async function runAmbientHookMode(opts) {
1668
1845
  .trim()
1669
1846
  .toLowerCase()
1670
1847
  .replace(/^\s*cd\s+[^&;]+(?:&&|;)\s*/, "")
1848
+ .replace(/\b2>\s*\/dev\/null\b/g, " ")
1849
+ .replace(/\b2>&1\b/g, " ")
1671
1850
  .trim();
1672
1851
  const isReadOnlyCmd =
1673
1852
  /^(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(
@@ -1729,12 +1908,37 @@ async function runAmbientHookMode(opts) {
1729
1908
  .slice(0, 1024);
1730
1909
 
1731
1910
  const whisperKey = sessionKey || scopeStateKey;
1732
- const isMidTurnContinuation =
1733
- rawEventName === "PreInvocation" &&
1734
- (Number(payload.invocationNum || 1) > 1 || Number(payload.executionNum || 1) > 1);
1735
1911
  if (!dedupState.stop_turn_by_session || typeof dedupState.stop_turn_by_session !== "object") {
1736
1912
  dedupState.stop_turn_by_session = {};
1737
1913
  }
1914
+ const existingStopTurnPre =
1915
+ whisperKey &&
1916
+ dedupState.stop_turn_by_session[whisperKey] &&
1917
+ typeof dedupState.stop_turn_by_session[whisperKey] === "object"
1918
+ ? dedupState.stop_turn_by_session[whisperKey]
1919
+ : null;
1920
+ const isStopRetryContinuation = Boolean(
1921
+ rawInput.includes("Stop hook blocked termination") ||
1922
+ (rawEventName === "PreInvocation" &&
1923
+ payload.invocationNum == null &&
1924
+ payload.executionNum == null &&
1925
+ existingStopTurnPre &&
1926
+ existingStopTurnPre.awaiting_stop_retry &&
1927
+ Date.now() - Number(existingStopTurnPre.blocked_at_ms || 0) < 120000)
1928
+ );
1929
+ if (rawEventName === "PreInvocation" && existingStopTurnPre && existingStopTurnPre.awaiting_stop_retry) {
1930
+ existingStopTurnPre.awaiting_stop_retry = false;
1931
+ try {
1932
+ fs.mkdirSync(path.dirname(dedupPath), { recursive: true });
1933
+ fs.writeFileSync(dedupPath, JSON.stringify(dedupState), "utf8");
1934
+ } catch {
1935
+ // ignore state persistence errors
1936
+ }
1937
+ }
1938
+ const isMidTurnContinuation =
1939
+ isStopRetryContinuation ||
1940
+ (rawEventName === "PreInvocation" &&
1941
+ (Number(payload.invocationNum || 1) > 1 || Number(payload.executionNum || 1) > 1));
1738
1942
  if (hookEvent === "UserPromptSubmit" && !isMidTurnContinuation && whisperKey) {
1739
1943
  const existingStopTurn = dedupState.stop_turn_by_session[whisperKey];
1740
1944
  if (
@@ -1777,7 +1981,6 @@ async function runAmbientHookMode(opts) {
1777
1981
  return;
1778
1982
  }
1779
1983
 
1780
- // Event deduplication (scoped to project/session/step and only persisted for non-actionable noise)
1781
1984
  const stepKey = String(
1782
1985
  payload.stepIdx ?? payload.invocationNum ?? payload.executionNum ?? ""
1783
1986
  );
@@ -1901,36 +2104,66 @@ async function runAmbientHookMode(opts) {
1901
2104
  delete dedupState.pending_tool_input_by_session[scopeStateKey];
1902
2105
  }
1903
2106
 
1904
- try {
1905
- const resp = await apiRequest(opts, "POST", "/v1/memory/intervene", {
1906
- hook_event_name: hookEvent,
1907
- prompt: payload.prompt || payload.lastUserInput || deltaText,
1908
- text: streamTextForIntervene,
1909
- ...(hookEvent === "Stop"
1910
- ? {
1911
- last_assistant_message: deltaText,
1912
- stop_hook_active: Boolean(payload.stop_hook_active),
1913
- turn_blocked_memory_ids: turnBlockedIds,
1914
- stop_retry_count: turnStopRetries,
1915
- }
1916
- : {}),
1917
- ...(isMidTurnContinuation ? { is_mid_turn_continuation: true } : {}),
1918
- tool_name: toolName,
1919
- tool_input: effectiveToolIn,
1920
- tool_response: payload.tool_response || payload.toolResponse || null,
1921
- whispered_memory_ids: whisperedMemoryIds,
1922
- ...(overriddenMemoryIds.length > 0 ? { overridden_memory_ids: overriddenMemoryIds } : {}),
1923
- commit_writes: isMidTurnContinuation ? false : true,
1924
- model: process.env.SLASHML_MODEL || undefined,
1925
- user_id: opts.userId,
1926
- ...(projectId ? { project_id: projectId } : {}),
1927
- session_id: whisperKey,
1928
- client_raw_tokens_delta: (telem.pending_raw_tokens_delta || 0) + strippedTokens,
1929
- client_dropped_tokens_delta: (telem.pending_dropped_tokens_delta || 0) + strippedTokens,
1930
- client_dropped_events_delta: telem.pending_dropped_events_delta || 0,
2107
+ const interveneReqBody = {
2108
+ hook_event_name: hookEvent,
2109
+ prompt: payload.prompt || payload.lastUserInput || deltaText,
2110
+ text: streamTextForIntervene,
2111
+ ...(hookEvent === "Stop"
2112
+ ? {
2113
+ last_assistant_message: deltaText,
2114
+ stop_hook_active: Boolean(payload.stop_hook_active),
2115
+ turn_blocked_memory_ids: turnBlockedIds,
2116
+ stop_retry_count: turnStopRetries,
2117
+ }
2118
+ : {}),
2119
+ ...(isMidTurnContinuation ? { is_mid_turn_continuation: true } : {}),
2120
+ tool_name: toolName,
2121
+ tool_input: effectiveToolIn,
2122
+ tool_response: payload.tool_response || payload.toolResponse || null,
2123
+ whispered_memory_ids: whisperedMemoryIds,
2124
+ ...(overriddenMemoryIds.length > 0 ? { overridden_memory_ids: overriddenMemoryIds } : {}),
2125
+ commit_writes: isMidTurnContinuation ? false : true,
2126
+ model: process.env.SLASHML_MODEL || undefined,
2127
+ user_id: opts.userId,
2128
+ ...(projectId ? { project_id: projectId } : {}),
2129
+ session_id: whisperKey,
2130
+ ...(opts.redactPolicy ? { redact_policy: opts.redactPolicy } : {}),
2131
+ ...(opts.redactScope ? { redact_scope: opts.redactScope } : {}),
2132
+ ...(opts.agentId ? { caller_agent_id: opts.agentId } : {}),
2133
+ client_raw_tokens_delta: (telem.pending_raw_tokens_delta || 0) + strippedTokens,
2134
+ client_dropped_tokens_delta: (telem.pending_dropped_tokens_delta || 0) + strippedTokens,
2135
+ client_dropped_events_delta: telem.pending_dropped_events_delta || 0,
2136
+ };
2137
+
2138
+ if (
2139
+ hookEvent === "PostToolUse" &&
2140
+ shouldUseHookDaemon(opts.baseUrl) &&
2141
+ process.env.SLASHML_SYNC_POST_TOOL !== "1"
2142
+ ) {
2143
+ telem.pending_raw_tokens_delta = 0;
2144
+ telem.pending_dropped_tokens_delta = 0;
2145
+ telem.pending_dropped_events_delta = 0;
2146
+ telem.conversation_tokens_processed = (telem.conversation_tokens_processed || 0) + rawEventTokens;
2147
+ telem.events_processed = (telem.events_processed || 0) + 1;
2148
+ saveHookTelemetry(telem);
2149
+ try {
2150
+ fs.mkdirSync(path.dirname(dedupPath), { recursive: true });
2151
+ fs.writeFileSync(dedupPath, JSON.stringify(dedupState), "utf8");
2152
+ } catch {
2153
+ // ignore state persistence errors
2154
+ }
2155
+ writeDefaultHookOutput(isGeminiHook, rawEventName, isCursorHook);
2156
+ await enqueueAsyncPostToolHook(opts, interveneReqBody, {
2157
+ dedupPath,
2158
+ rawEventTokens,
2159
+ deltaText,
2160
+ deltaHash,
1931
2161
  });
1932
- // Client-side per-memory Stop circuit breaker (defense-in-depth across server restarts/versions):
1933
- // at most 1 Stop block per memory_id per user prompt, and at most MAX_STOP_BLOCKS_PER_PROMPT total.
2162
+ return;
2163
+ }
2164
+
2165
+ try {
2166
+ const resp = await hookApiRequest(opts, "POST", "/v1/memory/intervene", interveneReqBody);
1934
2167
  if (
1935
2168
  hookEvent === "Stop" &&
1936
2169
  resp &&
@@ -1957,12 +2190,19 @@ async function runAmbientHookMode(opts) {
1957
2190
  resp.intervention_severity = "NONE";
1958
2191
  resp.intervention_message = null;
1959
2192
  resp.hook_output = {};
2193
+ if (whisperKey && dedupState.stop_turn_by_session[whisperKey]) {
2194
+ dedupState.stop_turn_by_session[whisperKey].awaiting_stop_retry = false;
2195
+ }
1960
2196
  } else if (whisperKey) {
1961
2197
  dedupState.stop_turn_by_session[whisperKey] = {
1962
2198
  blocked_ids: Array.from(new Set([...turnBlockedIds, ...novelStopIds])).slice(-16),
1963
2199
  retry_count: turnStopRetries + 1,
2200
+ awaiting_stop_retry: true,
2201
+ blocked_at_ms: Date.now(),
1964
2202
  };
1965
2203
  }
2204
+ } else if (hookEvent === "Stop" && whisperKey && dedupState.stop_turn_by_session[whisperKey]) {
2205
+ dedupState.stop_turn_by_session[whisperKey].awaiting_stop_retry = false;
1966
2206
  }
1967
2207
  telem.pending_raw_tokens_delta = 0;
1968
2208
  telem.pending_dropped_tokens_delta = 0;
@@ -2601,6 +2841,9 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2601
2841
  user_id: opts.userId || "default",
2602
2842
  project_id: projectId,
2603
2843
  session_id: sessionId,
2844
+ ...(opts.redactPolicy ? { redact_policy: opts.redactPolicy } : {}),
2845
+ ...(opts.redactScope ? { redact_scope: opts.redactScope } : {}),
2846
+ ...(opts.agentId ? { caller_agent_id: opts.agentId } : {}),
2604
2847
  });
2605
2848
  processedEvents += 1;
2606
2849
  telem.conversation_tokens_processed = (telem.conversation_tokens_processed || 0) + rawTok;
@@ -3527,6 +3770,13 @@ if (parsed.isStatus) {
3527
3770
  return;
3528
3771
  }
3529
3772
 
3773
+ if (parsed.isHookDaemon) {
3774
+ runHookDaemonServer()
3775
+ .then(() => {})
3776
+ .catch(() => process.exit(1));
3777
+ return;
3778
+ }
3779
+
3530
3780
  if (parsed.isHook) {
3531
3781
  runAmbientHookMode(parsed)
3532
3782
  .then(() => process.exit(process.exitCode || 0))
@@ -3579,15 +3829,43 @@ const STANDARD_TOOLS = [
3579
3829
  },
3580
3830
  {
3581
3831
  name: "forget_memory",
3582
- description: "Delete a specific memory by ID.",
3832
+ description: "Delete or permanently purge a specific memory by ID.",
3583
3833
  inputSchema: {
3584
3834
  type: "object",
3585
3835
  properties: {
3586
3836
  memory_id: { type: "string" },
3837
+ purge: {
3838
+ type: "boolean",
3839
+ description: "When true, irreversibly purges the memory and returns a bounded undo_token.",
3840
+ default: false,
3841
+ },
3842
+ reason: { type: "string" },
3587
3843
  },
3588
3844
  required: ["memory_id"],
3589
3845
  },
3590
3846
  },
3847
+ {
3848
+ name: "redact_memory",
3849
+ description:
3850
+ "Redact sensitive spans (secrets, PCI/financial, PII, PHI, commercial MNPI, legal/HR, security exploits) from raw text or an existing stored memory.",
3851
+ inputSchema: {
3852
+ type: "object",
3853
+ properties: {
3854
+ text: { type: "string", description: "Raw text to redact (when not redacting an existing memory_id)." },
3855
+ memory_id: { type: "string", description: "Optional stored memory ID to redact in place." },
3856
+ redact_policy: {
3857
+ oneOf: [{ type: "string" }, { type: "array", items: { type: "string" } }],
3858
+ description:
3859
+ "Preset ('tier1_secrets', 'soc2_coding', 'gdpr', 'hipaa', 'enterprise_strict') or array of bucket names.",
3860
+ },
3861
+ dry_run: {
3862
+ type: "boolean",
3863
+ description: "Preview redacted_text and redacted_spans without mutating stored memory.",
3864
+ default: false,
3865
+ },
3866
+ },
3867
+ },
3868
+ },
3591
3869
  {
3592
3870
  name: "dismiss_intervention",
3593
3871
  description:
@@ -3663,7 +3941,7 @@ const CODE_MODE_TOOLS = [
3663
3941
  {
3664
3942
  name: "execute_memory_code",
3665
3943
  description:
3666
- "Compact meta-tool (91% token savings) dispatching memory & code actions (`add_memory`, `search_memories`, `get_memories`, `forget_memory`, `index_repository`, `search_code_by_behavior`, `find_bug_candidates`, `intervene_memory`) to `/ ml` Cloud.",
3944
+ "Compact meta-tool (91% token savings) dispatching memory & code actions (`add_memory`, `search_memories`, `get_memories`, `forget_memory`, `redact_memory`, `index_repository`, `search_code_by_behavior`, `find_bug_candidates`, `intervene_memory`) to `/ ml` Cloud.",
3667
3945
  inputSchema: {
3668
3946
  type: "object",
3669
3947
  properties: {
@@ -3674,6 +3952,7 @@ const CODE_MODE_TOOLS = [
3674
3952
  "search_memories",
3675
3953
  "get_memories",
3676
3954
  "forget_memory",
3955
+ "redact_memory",
3677
3956
  "index_repository",
3678
3957
  "search_code_by_behavior",
3679
3958
  "find_bug_candidates",
@@ -3688,19 +3967,437 @@ const CODE_MODE_TOOLS = [
3688
3967
  },
3689
3968
  ];
3690
3969
 
3970
+ function getHookDaemonSocketPath() {
3971
+ if (process.platform === "win32") return null;
3972
+ if (process.env.SLASHML_DAEMON_SOCK) return process.env.SLASHML_DAEMON_SOCK;
3973
+ if (process.env.SLASHML_HOOK_SOCKET) return process.env.SLASHML_HOOK_SOCKET;
3974
+ const uidPart = typeof process.getuid === "function" ? String(process.getuid()) : "user";
3975
+ const candidate = path.join(os.homedir(), ".slashml", "run", `hook-daemon-${uidPart}.sock`);
3976
+ if (candidate.length <= 96) return candidate;
3977
+ const crypto = require("crypto");
3978
+ const digest = crypto.createHash("sha1").update(os.homedir()).digest("hex").slice(0, 12);
3979
+ return path.join(os.tmpdir(), `slashml-hd-${digest}.sock`);
3980
+ }
3981
+
3982
+ function shouldUseHookDaemon(baseUrl) {
3983
+ if (process.platform === "win32") return false;
3984
+ if (process.env.SLASHML_DISABLE_HOOK_DAEMON === "1") return false;
3985
+ if (process.env.SLASHML_FORCE_HOOK_DAEMON === "1") return true;
3986
+ const u = String(baseUrl || "");
3987
+ if (u.includes("127.0.0.1") || u.includes("localhost")) return false;
3988
+ return true;
3989
+ }
3990
+
3991
+ function spawnHookDaemonDetached() {
3992
+ try {
3993
+ const { spawn } = require("child_process");
3994
+ const child = spawn(process.execPath, [__filename, "--hook-daemon"], {
3995
+ detached: true,
3996
+ stdio: "ignore",
3997
+ env: process.env,
3998
+ });
3999
+ child.unref();
4000
+ } catch {
4001
+ // ignore background daemon spawn failures
4002
+ }
4003
+ }
4004
+
4005
+ function sendUnixDaemonRequest(sockPath, payload, timeoutMs = 25000) {
4006
+ const http = require("http");
4007
+ return new Promise((resolve, reject) => {
4008
+ const rawBody = JSON.stringify(payload);
4009
+ const req = http.request(
4010
+ {
4011
+ socketPath: sockPath,
4012
+ path: "/proxy",
4013
+ method: "POST",
4014
+ headers: {
4015
+ "Content-Type": "application/json",
4016
+ "Content-Length": Buffer.byteLength(rawBody),
4017
+ },
4018
+ timeout: timeoutMs,
4019
+ },
4020
+ (res) => {
4021
+ const chunks = [];
4022
+ res.on("data", (c) => chunks.push(Buffer.from(c)));
4023
+ res.on("end", () => {
4024
+ try {
4025
+ const parsedResp = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
4026
+ resolve({ httpStatus: res.statusCode || 200, data: parsedResp });
4027
+ } catch (err) {
4028
+ reject(err);
4029
+ }
4030
+ });
4031
+ }
4032
+ );
4033
+ req.on("timeout", () => {
4034
+ req.destroy(new Error("Hook daemon request timed out"));
4035
+ });
4036
+ req.on("error", reject);
4037
+ req.write(rawBody);
4038
+ req.end();
4039
+ });
4040
+ }
4041
+
4042
+ async function enqueueAsyncPostToolHook(opts, body, meta) {
4043
+ if (!opts.apiKey) return;
4044
+ const sockPath = getHookDaemonSocketPath();
4045
+ if (!sockPath) return;
4046
+ const headers = {
4047
+ Authorization: `Bearer ${opts.apiKey}`,
4048
+ "Content-Type": "application/json",
4049
+ "User-Agent": `slashml-cli-node/${PACKAGE_VERSION}`,
4050
+ };
4051
+ if (opts.agentId) {
4052
+ headers["X-SlashML-Agent-Id"] = opts.agentId;
4053
+ }
4054
+ const reqPayload = {
4055
+ method: "POST",
4056
+ url: `${opts.baseUrl}/v1/memory/intervene`,
4057
+ headers,
4058
+ body,
4059
+ fireAndForget: true,
4060
+ meta: {
4061
+ ...meta,
4062
+ telemPath:
4063
+ process.env.SLASHML_TELEMETRY_PATH ||
4064
+ path.join(os.homedir(), ".slashml", "telemetry.json"),
4065
+ },
4066
+ };
4067
+ try {
4068
+ await sendUnixDaemonRequest(sockPath, reqPayload, 400);
4069
+ return;
4070
+ } catch {
4071
+ spawnHookDaemonDetached();
4072
+ }
4073
+ for (let attempt = 0; attempt < 10; attempt++) {
4074
+ await new Promise((r) => setTimeout(r, 12));
4075
+ if (!fs.existsSync(sockPath)) continue;
4076
+ try {
4077
+ await sendUnixDaemonRequest(sockPath, reqPayload, 400);
4078
+ return;
4079
+ } catch {
4080
+ // retry briefly while daemon binds socket
4081
+ }
4082
+ }
4083
+ }
4084
+
4085
+ async function hookApiRequest(opts, method, urlPath, body) {
4086
+ if (!opts.apiKey) {
4087
+ throw new Error(
4088
+ "SlashML API key is required. Set SLASHML_API_KEY in your environment or pass --api-key."
4089
+ );
4090
+ }
4091
+ const sockPath = getHookDaemonSocketPath();
4092
+ if (sockPath && shouldUseHookDaemon(opts.baseUrl)) {
4093
+ const headers = {
4094
+ Authorization: `Bearer ${opts.apiKey}`,
4095
+ "Content-Type": "application/json",
4096
+ "User-Agent": `slashml-cli-node/${PACKAGE_VERSION}`,
4097
+ };
4098
+ if (opts.agentId) {
4099
+ headers["X-SlashML-Agent-Id"] = opts.agentId;
4100
+ }
4101
+ try {
4102
+ const { data } = await sendUnixDaemonRequest(
4103
+ sockPath,
4104
+ {
4105
+ method,
4106
+ url: `${opts.baseUrl}${urlPath}`,
4107
+ headers,
4108
+ body,
4109
+ fireAndForget: false,
4110
+ },
4111
+ 25000
4112
+ );
4113
+ if (data && typeof data.status === "number") {
4114
+ const parsedBody = data.text ? JSON.parse(data.text) : {};
4115
+ if (data.status < 200 || data.status >= 300) {
4116
+ throw new Error(`SlashML Cloud API error (HTTP ${data.status}): ${data.text || ""}`);
4117
+ }
4118
+ return parsedBody;
4119
+ }
4120
+ } catch (err) {
4121
+ if (err && String(err.message || "").startsWith("SlashML Cloud API error")) {
4122
+ throw err;
4123
+ }
4124
+ spawnHookDaemonDetached();
4125
+ }
4126
+ }
4127
+ return apiRequest(opts, method, urlPath, body);
4128
+ }
4129
+
4130
+ async function runHookDaemonServer() {
4131
+ const sockPath = getHookDaemonSocketPath();
4132
+ if (!sockPath) return;
4133
+ const http = require("http");
4134
+ const https = require("https");
4135
+ const net = require("net");
4136
+
4137
+ fs.mkdirSync(path.dirname(sockPath), { recursive: true });
4138
+ if (fs.existsSync(sockPath)) {
4139
+ const alive = await new Promise((resolve) => {
4140
+ const probe = net.createConnection(sockPath);
4141
+ probe.once("connect", () => {
4142
+ probe.end();
4143
+ resolve(true);
4144
+ });
4145
+ probe.once("error", () => resolve(false));
4146
+ });
4147
+ if (alive) {
4148
+ process.exit(0);
4149
+ }
4150
+ try {
4151
+ fs.unlinkSync(sockPath);
4152
+ } catch {
4153
+ // ignore stale socket removal race
4154
+ }
4155
+ }
4156
+
4157
+ const httpAgent = new http.Agent({ keepAlive: true, keepAliveMsecs: 60000, maxSockets: 16 });
4158
+ const httpsAgent = new https.Agent({ keepAlive: true, keepAliveMsecs: 60000, maxSockets: 16 });
4159
+
4160
+ function upstreamFetchViaAgent(method, targetUrl, headers, bodyObj, timeoutMs = 24000) {
4161
+ return new Promise((resolve, reject) => {
4162
+ const parsedUrl = new URL(targetUrl);
4163
+ const isHttps = parsedUrl.protocol === "https:";
4164
+ const mod = isHttps ? https : http;
4165
+ const rawBody = bodyObj !== undefined ? JSON.stringify(bodyObj) : "";
4166
+ const reqHeaders = { ...(headers || {}) };
4167
+ if (rawBody) {
4168
+ reqHeaders["Content-Length"] = Buffer.byteLength(rawBody);
4169
+ }
4170
+ const uReq = mod.request(
4171
+ {
4172
+ protocol: parsedUrl.protocol,
4173
+ hostname: parsedUrl.hostname,
4174
+ port: parsedUrl.port || (isHttps ? 443 : 80),
4175
+ path: `${parsedUrl.pathname}${parsedUrl.search}`,
4176
+ method: method || "POST",
4177
+ headers: reqHeaders,
4178
+ agent: isHttps ? httpsAgent : httpAgent,
4179
+ timeout: timeoutMs,
4180
+ },
4181
+ (uRes) => {
4182
+ const rChunks = [];
4183
+ uRes.on("data", (c) => rChunks.push(Buffer.from(c)));
4184
+ uRes.on("end", () => {
4185
+ resolve({
4186
+ status: uRes.statusCode || 200,
4187
+ text: Buffer.concat(rChunks).toString("utf8"),
4188
+ });
4189
+ });
4190
+ }
4191
+ );
4192
+ uReq.on("timeout", () => {
4193
+ uReq.destroy(new Error("Upstream API timed out"));
4194
+ });
4195
+ uReq.on("error", reject);
4196
+ if (rawBody) uReq.write(rawBody);
4197
+ uReq.end();
4198
+ });
4199
+ }
4200
+
4201
+ if (process.env.SLASHML_FORCE_HOOK_DAEMON !== "1") {
4202
+ try {
4203
+ const warmUrl = new URL(`${DEFAULT_BASE_URL}/health`);
4204
+ const warmReq = https.request(
4205
+ {
4206
+ hostname: warmUrl.hostname,
4207
+ port: 443,
4208
+ path: warmUrl.pathname,
4209
+ method: "GET",
4210
+ headers: { "User-Agent": `slashml-cli-node/${PACKAGE_VERSION}` },
4211
+ agent: httpsAgent,
4212
+ timeout: 5000,
4213
+ },
4214
+ (res) => res.resume()
4215
+ );
4216
+ warmReq.on("error", () => {});
4217
+ warmReq.end();
4218
+ } catch {
4219
+ // ignore connection error
4220
+ }
4221
+ }
4222
+
4223
+ let idleTimer = null;
4224
+ const idleLimitMs = Math.max(5000, Number(process.env.SLASHML_DAEMON_IDLE_MS || 900000));
4225
+ function touchIdle(server) {
4226
+ if (idleTimer) clearTimeout(idleTimer);
4227
+ idleTimer = setTimeout(() => {
4228
+ try {
4229
+ server.close();
4230
+ } catch {}
4231
+ try {
4232
+ if (fs.existsSync(sockPath)) fs.unlinkSync(sockPath);
4233
+ } catch {}
4234
+ process.exit(0);
4235
+ }, idleLimitMs);
4236
+ if (typeof idleTimer.unref === "function") idleTimer.unref();
4237
+ }
4238
+
4239
+ const server = http.createServer((req, res) => {
4240
+ touchIdle(server);
4241
+ if (req.method === "GET" && req.url === "/health") {
4242
+ res.writeHead(200, { "Content-Type": "application/json" });
4243
+ res.end(JSON.stringify({ ok: true, version: PACKAGE_VERSION, pid: process.pid }));
4244
+ return;
4245
+ }
4246
+ if (req.method === "POST" && req.url === "/shutdown") {
4247
+ res.writeHead(200, { "Content-Type": "application/json" });
4248
+ res.end(JSON.stringify({ ok: true }));
4249
+ setImmediate(() => {
4250
+ try {
4251
+ server.close();
4252
+ } catch {}
4253
+ try {
4254
+ if (fs.existsSync(sockPath)) fs.unlinkSync(sockPath);
4255
+ } catch {}
4256
+ process.exit(0);
4257
+ });
4258
+ return;
4259
+ }
4260
+ if (req.method === "POST" && req.url === "/proxy") {
4261
+ const chunks = [];
4262
+ req.on("data", (c) => chunks.push(Buffer.from(c)));
4263
+ req.on("end", async () => {
4264
+ let payload = {};
4265
+ try {
4266
+ payload = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
4267
+ } catch {
4268
+ res.writeHead(400, { "Content-Type": "application/json" });
4269
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
4270
+ return;
4271
+ }
4272
+ if (payload.fireAndForget) {
4273
+ res.writeHead(202, { "Content-Type": "application/json" });
4274
+ res.end(JSON.stringify({ queued: true }));
4275
+ try {
4276
+ const up = await upstreamFetchViaAgent(
4277
+ payload.method || "POST",
4278
+ payload.url,
4279
+ payload.headers,
4280
+ payload.body
4281
+ );
4282
+ if (up.status >= 200 && up.status < 300 && up.text && payload.meta) {
4283
+ const respObj = JSON.parse(up.text);
4284
+ const { dedupPath, telemPath, rawEventTokens, deltaText, deltaHash } = payload.meta;
4285
+ if (telemPath) {
4286
+ let tObj = {};
4287
+ try {
4288
+ if (fs.existsSync(telemPath)) {
4289
+ tObj = JSON.parse(fs.readFileSync(telemPath, "utf8")) || {};
4290
+ }
4291
+ } catch {}
4292
+ if (respObj && (respObj.should_write || respObj.should_intervene)) {
4293
+ const spanTok = estimateTokens(respObj.extracted_write_span || deltaText || "");
4294
+ tObj.noise_tokens_filtered =
4295
+ (tObj.noise_tokens_filtered || 0) + Math.max(0, (rawEventTokens || 0) - spanTok);
4296
+ if (respObj.should_write) {
4297
+ tObj.memories_assimilated = (tObj.memories_assimilated || 0) + 1;
4298
+ if (respObj.write_novelty_action === "SUPERSEDES") {
4299
+ tObj.memories_superseded = (tObj.memories_superseded || 0) + 1;
4300
+ }
4301
+ }
4302
+ } else {
4303
+ tObj.noise_tokens_filtered =
4304
+ (tObj.noise_tokens_filtered || 0) + (rawEventTokens || 0);
4305
+ tObj.events_filtered_noise = (tObj.events_filtered_noise || 0) + 1;
4306
+ }
4307
+ try {
4308
+ fs.mkdirSync(path.dirname(telemPath), { recursive: true });
4309
+ fs.writeFileSync(telemPath, JSON.stringify(tObj), "utf8");
4310
+ } catch {}
4311
+ }
4312
+ if (dedupPath) {
4313
+ let dObj = { hashes: [] };
4314
+ try {
4315
+ if (fs.existsSync(dedupPath)) {
4316
+ dObj = JSON.parse(fs.readFileSync(dedupPath, "utf8")) || { hashes: [] };
4317
+ }
4318
+ } catch {}
4319
+ if (respObj && respObj.should_write) {
4320
+ dObj.hashes = [];
4321
+ } else if (deltaHash) {
4322
+ dObj.hashes = [
4323
+ ...(Array.isArray(dObj.hashes) ? dObj.hashes.slice(-63) : []),
4324
+ deltaHash,
4325
+ ];
4326
+ }
4327
+ try {
4328
+ fs.mkdirSync(path.dirname(dedupPath), { recursive: true });
4329
+ fs.writeFileSync(dedupPath, JSON.stringify(dObj), "utf8");
4330
+ } catch {}
4331
+ }
4332
+ }
4333
+ } catch {
4334
+ // fail-open on background PostToolUse errors
4335
+ }
4336
+ return;
4337
+ }
4338
+ try {
4339
+ const up = await upstreamFetchViaAgent(
4340
+ payload.method || "POST",
4341
+ payload.url,
4342
+ payload.headers,
4343
+ payload.body
4344
+ );
4345
+ res.writeHead(200, { "Content-Type": "application/json" });
4346
+ res.end(JSON.stringify(up));
4347
+ } catch (err) {
4348
+ res.writeHead(502, { "Content-Type": "application/json" });
4349
+ res.end(JSON.stringify({ error: String((err && err.message) || err) }));
4350
+ }
4351
+ });
4352
+ return;
4353
+ }
4354
+ res.writeHead(404, { "Content-Type": "application/json" });
4355
+ res.end(JSON.stringify({ error: "Not found" }));
4356
+ });
4357
+
4358
+ const cleanup = () => {
4359
+ try {
4360
+ if (fs.existsSync(sockPath)) fs.unlinkSync(sockPath);
4361
+ } catch {}
4362
+ };
4363
+ process.on("SIGTERM", () => {
4364
+ cleanup();
4365
+ process.exit(0);
4366
+ });
4367
+ process.on("SIGINT", () => {
4368
+ cleanup();
4369
+ process.exit(0);
4370
+ });
4371
+
4372
+ await new Promise((resolve, reject) => {
4373
+ server.once("error", reject);
4374
+ server.listen(sockPath, () => {
4375
+ try {
4376
+ fs.chmodSync(sockPath, 0o600);
4377
+ } catch {}
4378
+ touchIdle(server);
4379
+ resolve();
4380
+ });
4381
+ });
4382
+ }
4383
+
3691
4384
  async function apiRequest(opts, method, urlPath, body) {
3692
4385
  if (!opts.apiKey) {
3693
4386
  throw new Error(
3694
4387
  "SlashML API key is required. Set SLASHML_API_KEY in your environment or pass --api-key."
3695
4388
  );
3696
4389
  }
4390
+ const headers = {
4391
+ Authorization: `Bearer ${opts.apiKey}`,
4392
+ "Content-Type": "application/json",
4393
+ "User-Agent": `slashml-cli-node/${PACKAGE_VERSION}`,
4394
+ };
4395
+ if (opts.agentId) {
4396
+ headers["X-SlashML-Agent-Id"] = opts.agentId;
4397
+ }
3697
4398
  const res = await fetch(`${opts.baseUrl}${urlPath}`, {
3698
4399
  method,
3699
- headers: {
3700
- Authorization: `Bearer ${opts.apiKey}`,
3701
- "Content-Type": "application/json",
3702
- "User-Agent": "slashml-cli-node/1.0.0",
3703
- },
4400
+ headers,
3704
4401
  body: body !== undefined ? JSON.stringify(body) : undefined,
3705
4402
  });
3706
4403
  const text = await res.text();
@@ -3864,6 +4561,16 @@ async function dispatchTool(opts, name, args = {}) {
3864
4561
  return dispatchTool(opts, args.action, args.params || {});
3865
4562
  }
3866
4563
  const uid = args.user_id || opts.userId;
4564
+ const effRedactPolicy = args.redact_policy !== undefined ? args.redact_policy : opts.redactPolicy;
4565
+ const effRedactScope = args.redact_scope !== undefined ? args.redact_scope : opts.redactScope;
4566
+ const effAgentId = args.caller_agent_id || opts.agentId || null;
4567
+
4568
+ function withLifecycle(payload) {
4569
+ if (effRedactPolicy) payload.redact_policy = effRedactPolicy;
4570
+ if (effRedactScope) payload.redact_scope = effRedactScope;
4571
+ if (effAgentId) payload.caller_agent_id = effAgentId;
4572
+ return payload;
4573
+ }
3867
4574
 
3868
4575
  if (name === "add_memory") {
3869
4576
  const rawText = args.text !== undefined ? args.text : args.messages;
@@ -3877,12 +4584,17 @@ async function dispatchTool(opts, name, args = {}) {
3877
4584
  ...(args.metadata ? { metadata: args.metadata } : {}),
3878
4585
  },
3879
4586
  ];
3880
- return apiRequest(opts, "POST", "/v1/memories", {
3881
- messages: messagesPayload,
3882
- user_id: uid,
3883
- memory_id: args.memory_id,
3884
- metadata: args.metadata || {},
3885
- });
4587
+ return apiRequest(
4588
+ opts,
4589
+ "POST",
4590
+ "/v1/memories",
4591
+ withLifecycle({
4592
+ messages: messagesPayload,
4593
+ user_id: uid,
4594
+ memory_id: args.memory_id,
4595
+ metadata: args.metadata || {},
4596
+ })
4597
+ );
3886
4598
  }
3887
4599
  if (name === "search_memories") {
3888
4600
  const k = Number(args.limit || args.top_k || 5);
@@ -3891,24 +4603,55 @@ async function dispatchTool(opts, name, args = {}) {
3891
4603
  ...(args.include_code !== undefined ? { include_code: Boolean(args.include_code) } : {}),
3892
4604
  ...(args.kind ? { kind: String(args.kind) } : {}),
3893
4605
  };
3894
- return apiRequest(opts, "POST", "/v1/memories/search", {
3895
- query: args.query,
3896
- user_id: uid,
3897
- limit: k,
3898
- top_k: k,
3899
- ...(Object.keys(mergedFilters).length > 0 ? { filters: mergedFilters } : {}),
3900
- });
4606
+ return apiRequest(
4607
+ opts,
4608
+ "POST",
4609
+ "/v1/memories/search",
4610
+ withLifecycle({
4611
+ query: args.query,
4612
+ user_id: uid,
4613
+ limit: k,
4614
+ top_k: k,
4615
+ ...(Object.keys(mergedFilters).length > 0 ? { filters: mergedFilters } : {}),
4616
+ })
4617
+ );
3901
4618
  }
3902
4619
  if (name === "get_memories") {
3903
4620
  const paramsObj = { user_id: uid, limit: String(args.limit || 50) };
3904
4621
  if (args.include_code !== undefined) paramsObj.include_code = String(Boolean(args.include_code));
3905
4622
  if (args.kind) paramsObj.kind = String(args.kind);
4623
+ if (effRedactPolicy) {
4624
+ paramsObj.redact_policy = Array.isArray(effRedactPolicy)
4625
+ ? effRedactPolicy.join(",")
4626
+ : String(effRedactPolicy);
4627
+ }
4628
+ if (effRedactScope) paramsObj.redact_scope = String(effRedactScope);
3906
4629
  const q = new URLSearchParams(paramsObj);
3907
4630
  return apiRequest(opts, "GET", `/v1/memories?${q.toString()}`);
3908
4631
  }
3909
4632
  if (name === "forget_memory") {
4633
+ if (args.purge) {
4634
+ return apiRequest(
4635
+ opts,
4636
+ "POST",
4637
+ "/v1/memory/purge",
4638
+ withLifecycle({
4639
+ memory_ids: [String(args.memory_id)],
4640
+ ...(args.reason ? { reason: String(args.reason) } : {}),
4641
+ ...(args.dry_run !== undefined ? { dry_run: Boolean(args.dry_run) } : {}),
4642
+ })
4643
+ );
4644
+ }
3910
4645
  return apiRequest(opts, "DELETE", `/v1/memories/${encodeURIComponent(args.memory_id)}`);
3911
4646
  }
4647
+ if (name === "redact_memory" || name === "sanitize_memory") {
4648
+ const body = {};
4649
+ if (args.text !== undefined) body.text = String(args.text);
4650
+ if (args.memory_id) body.memory_id = String(args.memory_id);
4651
+ if (args.explicit_spans !== undefined) body.explicit_spans = args.explicit_spans;
4652
+ if (args.dry_run !== undefined) body.dry_run = Boolean(args.dry_run);
4653
+ return apiRequest(opts, "POST", "/v1/memory/redact", withLifecycle(body));
4654
+ }
3912
4655
  if (name === "index_repository") {
3913
4656
  const rawPath = args.path || args.repo_path || opts.repo || ".";
3914
4657
  const repoPath = path.resolve(rawPath);
@@ -3932,10 +4675,15 @@ async function dispatchTool(opts, name, args = {}) {
3932
4675
  let lastRes = {};
3933
4676
  for (let i = 0; i < documents.length; i += BATCH_SIZE) {
3934
4677
  const batch = documents.slice(i, i + BATCH_SIZE);
3935
- const res = await apiRequest(opts, "POST", "/v1/memory/ingest", {
3936
- documents: batch,
3937
- user_id: uid,
3938
- });
4678
+ const res = await apiRequest(
4679
+ opts,
4680
+ "POST",
4681
+ "/v1/memory/ingest",
4682
+ withLifecycle({
4683
+ documents: batch,
4684
+ user_id: uid,
4685
+ })
4686
+ );
3939
4687
  lastRes = res || {};
3940
4688
  totalIngested += Number(res?.ingested_count ?? res?.count ?? batch.length);
3941
4689
  totalTokens += Number(res?.tokens_processed ?? 0);
@@ -3955,26 +4703,36 @@ async function dispatchTool(opts, name, args = {}) {
3955
4703
  }
3956
4704
  if (name === "search_code_by_behavior") {
3957
4705
  const k = Number(args.top_k || args.limit || 5);
3958
- return apiRequest(opts, "POST", "/v1/memories/search", {
3959
- query: args.query,
3960
- user_id: uid,
3961
- limit: k,
3962
- top_k: k,
3963
- filters: { kind: "code_symbol", ...(args.language ? { language: args.language } : {}) },
3964
- });
4706
+ return apiRequest(
4707
+ opts,
4708
+ "POST",
4709
+ "/v1/memories/search",
4710
+ withLifecycle({
4711
+ query: args.query,
4712
+ user_id: uid,
4713
+ limit: k,
4714
+ top_k: k,
4715
+ filters: { kind: "code_symbol", ...(args.language ? { language: args.language } : {}) },
4716
+ })
4717
+ );
3965
4718
  }
3966
4719
  if (name === "find_bug_candidates") {
3967
4720
  const k = Number(args.top_k || args.limit || 5);
3968
4721
  const combinedQuery = args.stack_trace
3969
4722
  ? `${args.bug_description}\n${args.stack_trace}`
3970
4723
  : args.bug_description;
3971
- return apiRequest(opts, "POST", "/v1/memories/search", {
3972
- query: combinedQuery,
3973
- user_id: uid,
3974
- limit: k,
3975
- top_k: k,
3976
- filters: { kind: "code_symbol" },
3977
- });
4724
+ return apiRequest(
4725
+ opts,
4726
+ "POST",
4727
+ "/v1/memories/search",
4728
+ withLifecycle({
4729
+ query: combinedQuery,
4730
+ user_id: uid,
4731
+ limit: k,
4732
+ top_k: k,
4733
+ filters: { kind: "code_symbol" },
4734
+ })
4735
+ );
3978
4736
  }
3979
4737
  if (name === "intervene_memory") {
3980
4738
  const rawText = String(args.text || args.prompt || "");
@@ -3987,21 +4745,26 @@ async function dispatchTool(opts, name, args = {}) {
3987
4745
  ...(Array.isArray(args.dismiss_memory_ids) ? args.dismiss_memory_ids : []),
3988
4746
  ...(args.override_memory_id ? [String(args.override_memory_id)] : []),
3989
4747
  ].filter(Boolean);
3990
- return apiRequest(opts, "POST", "/v1/memory/intervene", {
3991
- hook_event_name: args.hook_event_name || "UserPromptSubmit",
3992
- prompt: args.prompt || rawText,
3993
- text: rawText,
3994
- tool_name: args.tool_name || null,
3995
- tool_input: args.tool_input || null,
3996
- tool_response: args.tool_response || null,
3997
- ...(overriddenIds.length > 0 ? { overridden_memory_ids: overriddenIds } : {}),
3998
- model: args.model || process.env.SLASHML_MODEL || undefined,
3999
- user_id: uid,
4000
- ...(resolvedProjectId ? { project_id: String(resolvedProjectId) } : {}),
4001
- ...(resolvedSessionId ? { session_id: String(resolvedSessionId) } : {}),
4002
- commit_writes: args.commit_writes !== undefined ? Boolean(args.commit_writes) : true,
4003
- top_k: Number(args.top_k || args.limit || 5),
4004
- });
4748
+ return apiRequest(
4749
+ opts,
4750
+ "POST",
4751
+ "/v1/memory/intervene",
4752
+ withLifecycle({
4753
+ hook_event_name: args.hook_event_name || "UserPromptSubmit",
4754
+ prompt: args.prompt || rawText,
4755
+ text: rawText,
4756
+ tool_name: args.tool_name || null,
4757
+ tool_input: args.tool_input || null,
4758
+ tool_response: args.tool_response || null,
4759
+ ...(overriddenIds.length > 0 ? { overridden_memory_ids: overriddenIds } : {}),
4760
+ model: args.model || process.env.SLASHML_MODEL || undefined,
4761
+ user_id: uid,
4762
+ ...(resolvedProjectId ? { project_id: String(resolvedProjectId) } : {}),
4763
+ ...(resolvedSessionId ? { session_id: String(resolvedSessionId) } : {}),
4764
+ commit_writes: args.commit_writes !== undefined ? Boolean(args.commit_writes) : true,
4765
+ top_k: Number(args.top_k || args.limit || 5),
4766
+ })
4767
+ );
4005
4768
  }
4006
4769
  if (name === "dismiss_intervention") {
4007
4770
  const memIds = [
@@ -4144,7 +4907,12 @@ rl.on("line", (line) => {
4144
4907
  const tools = parsed.codeMode
4145
4908
  ? CODE_MODE_TOOLS
4146
4909
  : parsed.codeOnly
4147
- ? STANDARD_TOOLS.slice(5)
4910
+ ? STANDARD_TOOLS.filter(
4911
+ (t) =>
4912
+ t.name === "index_repository" ||
4913
+ t.name === "search_code_by_behavior" ||
4914
+ t.name === "find_bug_candidates"
4915
+ )
4148
4916
  : parsed.passiveWrites
4149
4917
  ? STANDARD_TOOLS.filter((t) => t.name !== "add_memory")
4150
4918
  : STANDARD_TOOLS;