@slashml/memory 1.0.14 → 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 +679 -55
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/src/index.ts +1 -1
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
|
+
const PACKAGE_VERSION = "1.0.15";
|
|
14
14
|
const MAX_STOP_BLOCKS_PER_PROMPT = 3;
|
|
15
15
|
|
|
16
16
|
function printHelp() {
|
|
@@ -198,6 +198,7 @@ function parseCliArgs(argv) {
|
|
|
198
198
|
let verifyCode = null;
|
|
199
199
|
let writeEnv = false;
|
|
200
200
|
let isHook = false;
|
|
201
|
+
let isHookDaemon = false;
|
|
201
202
|
let hookEvent = null;
|
|
202
203
|
let isInstallHooks = false;
|
|
203
204
|
let isStatus = false;
|
|
@@ -227,6 +228,8 @@ function parseCliArgs(argv) {
|
|
|
227
228
|
isInit = true;
|
|
228
229
|
} else if (arg === "--hook" || arg === "hook") {
|
|
229
230
|
isHook = true;
|
|
231
|
+
} else if (arg === "--hook-daemon") {
|
|
232
|
+
isHookDaemon = true;
|
|
230
233
|
} else if (arg === "--hook-event" && i + 1 < argv.length) {
|
|
231
234
|
hookEvent = argv[++i];
|
|
232
235
|
} else if (arg === "--install-hooks" || arg === "install-hooks") {
|
|
@@ -326,6 +329,7 @@ function parseCliArgs(argv) {
|
|
|
326
329
|
verifyCode,
|
|
327
330
|
writeEnv,
|
|
328
331
|
isHook,
|
|
332
|
+
isHookDaemon,
|
|
329
333
|
hookEvent,
|
|
330
334
|
isInstallHooks,
|
|
331
335
|
isStatus,
|
|
@@ -659,11 +663,64 @@ function upsertSlashmlRuleBlock(filePath, bodyText = AMBIENT_RULE_MARKDOWN) {
|
|
|
659
663
|
return true;
|
|
660
664
|
}
|
|
661
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
|
+
|
|
662
719
|
function installAmbientHooks(apiKey, opts = {}) {
|
|
663
720
|
const quiet = Boolean(opts && opts.quiet);
|
|
664
721
|
const onlyIfDirExists = Boolean(opts && opts.onlyIfDirExists);
|
|
665
722
|
const home = os.homedir();
|
|
666
|
-
const
|
|
723
|
+
const { nodeBin, launcherPath, hookCmd } = ensureHookLauncherInstalled(home);
|
|
667
724
|
|
|
668
725
|
// 1. Claude Code (~/.claude/settings.json + ~/.claude/CLAUDE.md)
|
|
669
726
|
const claudeDir = path.join(home, ".claude");
|
|
@@ -683,14 +740,32 @@ function installAmbientHooks(apiKey, opts = {}) {
|
|
|
683
740
|
}
|
|
684
741
|
let changed = false;
|
|
685
742
|
for (const eventName of ["UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"]) {
|
|
743
|
+
const targetEventCmd = `${hookCmd} --hook-event ${eventName}`;
|
|
686
744
|
if (!quiet || !Array.isArray(settings.hooks[eventName]) || settings.hooks[eventName].length === 0) {
|
|
687
745
|
settings.hooks[eventName] = [
|
|
688
746
|
{
|
|
689
747
|
matcher: ".*",
|
|
690
|
-
hooks: [{ type: "command", command:
|
|
748
|
+
hooks: [{ type: "command", command: targetEventCmd, timeout: 30 }],
|
|
691
749
|
},
|
|
692
750
|
];
|
|
693
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
|
+
}
|
|
694
769
|
}
|
|
695
770
|
}
|
|
696
771
|
if (apiKey && (!quiet || !settings.env || !settings.env.SLASHML_API_KEY)) {
|
|
@@ -781,30 +856,61 @@ function installAmbientHooks(apiKey, opts = {}) {
|
|
|
781
856
|
UserPromptSubmit: [
|
|
782
857
|
{
|
|
783
858
|
matcher: ".*",
|
|
784
|
-
hooks: [{ type: "command", command: `${hookCmd} --hook-event UserPromptSubmit`, timeout:
|
|
859
|
+
hooks: [{ type: "command", command: `${hookCmd} --hook-event UserPromptSubmit`, timeout: 30 }],
|
|
785
860
|
},
|
|
786
861
|
],
|
|
787
862
|
PreToolUse: [
|
|
788
863
|
{
|
|
789
864
|
matcher: ".*",
|
|
790
|
-
hooks: [{ type: "command", command: `${hookCmd} --hook-event PreToolUse`, timeout:
|
|
865
|
+
hooks: [{ type: "command", command: `${hookCmd} --hook-event PreToolUse`, timeout: 30 }],
|
|
791
866
|
},
|
|
792
867
|
],
|
|
793
868
|
PostToolUse: [
|
|
794
869
|
{
|
|
795
870
|
matcher: ".*",
|
|
796
|
-
hooks: [{ type: "command", command: `${hookCmd} --hook-event PostToolUse`, timeout:
|
|
871
|
+
hooks: [{ type: "command", command: `${hookCmd} --hook-event PostToolUse`, timeout: 30 }],
|
|
797
872
|
},
|
|
798
873
|
],
|
|
799
874
|
Stop: [
|
|
800
875
|
{
|
|
801
876
|
matcher: ".*",
|
|
802
|
-
hooks: [{ type: "command", command: `${hookCmd} --hook-event Stop`, timeout:
|
|
877
|
+
hooks: [{ type: "command", command: `${hookCmd} --hook-event Stop`, timeout: 30 }],
|
|
803
878
|
},
|
|
804
879
|
],
|
|
805
880
|
},
|
|
806
881
|
};
|
|
807
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
|
+
}
|
|
808
914
|
}
|
|
809
915
|
try {
|
|
810
916
|
upsertSlashmlRuleBlock(path.join(codexDir, "AGENTS.md"));
|
|
@@ -850,7 +956,7 @@ function installAmbientHooks(apiKey, opts = {}) {
|
|
|
850
956
|
{
|
|
851
957
|
type: "command",
|
|
852
958
|
command: `${hookCmd} --hook-event PreInvocation`,
|
|
853
|
-
timeout:
|
|
959
|
+
timeout: 30,
|
|
854
960
|
},
|
|
855
961
|
],
|
|
856
962
|
PreToolUse: [
|
|
@@ -860,7 +966,7 @@ function installAmbientHooks(apiKey, opts = {}) {
|
|
|
860
966
|
{
|
|
861
967
|
type: "command",
|
|
862
968
|
command: `${hookCmd} --hook-event PreToolUse`,
|
|
863
|
-
timeout:
|
|
969
|
+
timeout: 30,
|
|
864
970
|
},
|
|
865
971
|
],
|
|
866
972
|
},
|
|
@@ -872,7 +978,7 @@ function installAmbientHooks(apiKey, opts = {}) {
|
|
|
872
978
|
{
|
|
873
979
|
type: "command",
|
|
874
980
|
command: `${hookCmd} --hook-event PostToolUse`,
|
|
875
|
-
timeout:
|
|
981
|
+
timeout: 30,
|
|
876
982
|
},
|
|
877
983
|
],
|
|
878
984
|
},
|
|
@@ -881,12 +987,45 @@ function installAmbientHooks(apiKey, opts = {}) {
|
|
|
881
987
|
{
|
|
882
988
|
type: "command",
|
|
883
989
|
command: `${hookCmd} --hook-event Stop`,
|
|
884
|
-
timeout:
|
|
990
|
+
timeout: 30,
|
|
885
991
|
},
|
|
886
992
|
],
|
|
887
993
|
},
|
|
888
994
|
};
|
|
889
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
|
+
}
|
|
890
1029
|
}
|
|
891
1030
|
const geminiPluginJsonPath = path.join(geminiPluginDir, "plugin.json");
|
|
892
1031
|
if (!fs.existsSync(geminiPluginJsonPath)) {
|
|
@@ -922,10 +1061,10 @@ function installAmbientHooks(apiKey, opts = {}) {
|
|
|
922
1061
|
|
|
923
1062
|
function runHook(event, payload) {
|
|
924
1063
|
try {
|
|
925
|
-
const res = spawnSync(
|
|
1064
|
+
const res = spawnSync(${JSON.stringify(nodeBin)}, [${JSON.stringify(launcherPath)}, "--hook", "--hook-event", event], {
|
|
926
1065
|
input: JSON.stringify({ hook_event_name: event, ...payload }),
|
|
927
1066
|
encoding: "utf8",
|
|
928
|
-
timeout:
|
|
1067
|
+
timeout: 30000,
|
|
929
1068
|
});
|
|
930
1069
|
if (res.stdout && res.stdout.trim().startsWith("{")) {
|
|
931
1070
|
return JSON.parse(res.stdout.trim());
|
|
@@ -1018,7 +1157,7 @@ export default SlashMLMemoryPlugin;
|
|
|
1018
1157
|
const hooksDir = path.join(hermesDir, "agent-hooks");
|
|
1019
1158
|
fs.mkdirSync(hooksDir, { recursive: true });
|
|
1020
1159
|
const scriptPath = path.join(hooksDir, "slashml-hook.sh");
|
|
1021
|
-
const scriptBody = `#!/usr/bin/env bash\nexec
|
|
1160
|
+
const scriptBody = `#!/usr/bin/env bash\nexec ${hookCmd} --hook-event "\${1:-pre_tool_call}"\n`;
|
|
1022
1161
|
if (!quiet || !fs.existsSync(scriptPath)) {
|
|
1023
1162
|
fs.writeFileSync(scriptPath, scriptBody, { encoding: "utf8", mode: 0o755 });
|
|
1024
1163
|
fs.chmodSync(scriptPath, 0o755);
|
|
@@ -1062,16 +1201,16 @@ export default SlashMLMemoryPlugin;
|
|
|
1062
1201
|
"hooks:",
|
|
1063
1202
|
` pre_llm_call:`,
|
|
1064
1203
|
` - command: "${scriptPath} pre_llm_call"`,
|
|
1065
|
-
` timeout:
|
|
1204
|
+
` timeout: 30`,
|
|
1066
1205
|
` pre_tool_call:`,
|
|
1067
1206
|
` - command: "${scriptPath} pre_tool_call"`,
|
|
1068
|
-
` timeout:
|
|
1207
|
+
` timeout: 30`,
|
|
1069
1208
|
` post_tool_call:`,
|
|
1070
1209
|
` - command: "${scriptPath} post_tool_call"`,
|
|
1071
|
-
` timeout:
|
|
1210
|
+
` timeout: 30`,
|
|
1072
1211
|
` post_llm_call:`,
|
|
1073
1212
|
` - command: "${scriptPath} post_llm_call"`,
|
|
1074
|
-
` timeout:
|
|
1213
|
+
` timeout: 30`,
|
|
1075
1214
|
].join("\n");
|
|
1076
1215
|
yamlText = yamlText.trim() ? `${yamlText.replace(/\n*$/, "")}\n\n${hooksBlock}\n` : `${hooksBlock}\n`;
|
|
1077
1216
|
fs.writeFileSync(configYamlPath, yamlText, "utf8");
|
|
@@ -1393,6 +1532,11 @@ function extractWhisperedContextFromCurrentTurn(transcriptPath) {
|
|
|
1393
1532
|
if (matches) {
|
|
1394
1533
|
for (const m of matches) ids.add(m);
|
|
1395
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
|
+
}
|
|
1396
1540
|
}
|
|
1397
1541
|
} catch {
|
|
1398
1542
|
// ignore partial line at start of buffer
|
|
@@ -1565,7 +1709,6 @@ async function runAmbientHookMode(opts) {
|
|
|
1565
1709
|
}
|
|
1566
1710
|
}
|
|
1567
1711
|
|
|
1568
|
-
// Enforce hard 3-retry safety ceiling locally if harness passes an explicit loop_count >= 3
|
|
1569
1712
|
if (hookEvent === "Stop" && Number(payload.loop_count || 0) >= MAX_STOP_BLOCKS_PER_PROMPT) {
|
|
1570
1713
|
writeDefaultHookOutput(isGeminiHook, rawEventName, isCursorHook);
|
|
1571
1714
|
return;
|
|
@@ -1702,6 +1845,8 @@ async function runAmbientHookMode(opts) {
|
|
|
1702
1845
|
.trim()
|
|
1703
1846
|
.toLowerCase()
|
|
1704
1847
|
.replace(/^\s*cd\s+[^&;]+(?:&&|;)\s*/, "")
|
|
1848
|
+
.replace(/\b2>\s*\/dev\/null\b/g, " ")
|
|
1849
|
+
.replace(/\b2>&1\b/g, " ")
|
|
1705
1850
|
.trim();
|
|
1706
1851
|
const isReadOnlyCmd =
|
|
1707
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(
|
|
@@ -1763,12 +1908,37 @@ async function runAmbientHookMode(opts) {
|
|
|
1763
1908
|
.slice(0, 1024);
|
|
1764
1909
|
|
|
1765
1910
|
const whisperKey = sessionKey || scopeStateKey;
|
|
1766
|
-
const isMidTurnContinuation =
|
|
1767
|
-
rawEventName === "PreInvocation" &&
|
|
1768
|
-
(Number(payload.invocationNum || 1) > 1 || Number(payload.executionNum || 1) > 1);
|
|
1769
1911
|
if (!dedupState.stop_turn_by_session || typeof dedupState.stop_turn_by_session !== "object") {
|
|
1770
1912
|
dedupState.stop_turn_by_session = {};
|
|
1771
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));
|
|
1772
1942
|
if (hookEvent === "UserPromptSubmit" && !isMidTurnContinuation && whisperKey) {
|
|
1773
1943
|
const existingStopTurn = dedupState.stop_turn_by_session[whisperKey];
|
|
1774
1944
|
if (
|
|
@@ -1811,7 +1981,6 @@ async function runAmbientHookMode(opts) {
|
|
|
1811
1981
|
return;
|
|
1812
1982
|
}
|
|
1813
1983
|
|
|
1814
|
-
// Event deduplication (scoped to project/session/step and only persisted for non-actionable noise)
|
|
1815
1984
|
const stepKey = String(
|
|
1816
1985
|
payload.stepIdx ?? payload.invocationNum ?? payload.executionNum ?? ""
|
|
1817
1986
|
);
|
|
@@ -1935,39 +2104,66 @@ async function runAmbientHookMode(opts) {
|
|
|
1935
2104
|
delete dedupState.pending_tool_input_by_session[scopeStateKey];
|
|
1936
2105
|
}
|
|
1937
2106
|
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
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,
|
|
1968
2161
|
});
|
|
1969
|
-
|
|
1970
|
-
|
|
2162
|
+
return;
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
try {
|
|
2166
|
+
const resp = await hookApiRequest(opts, "POST", "/v1/memory/intervene", interveneReqBody);
|
|
1971
2167
|
if (
|
|
1972
2168
|
hookEvent === "Stop" &&
|
|
1973
2169
|
resp &&
|
|
@@ -1994,12 +2190,19 @@ async function runAmbientHookMode(opts) {
|
|
|
1994
2190
|
resp.intervention_severity = "NONE";
|
|
1995
2191
|
resp.intervention_message = null;
|
|
1996
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
|
+
}
|
|
1997
2196
|
} else if (whisperKey) {
|
|
1998
2197
|
dedupState.stop_turn_by_session[whisperKey] = {
|
|
1999
2198
|
blocked_ids: Array.from(new Set([...turnBlockedIds, ...novelStopIds])).slice(-16),
|
|
2000
2199
|
retry_count: turnStopRetries + 1,
|
|
2200
|
+
awaiting_stop_retry: true,
|
|
2201
|
+
blocked_at_ms: Date.now(),
|
|
2001
2202
|
};
|
|
2002
2203
|
}
|
|
2204
|
+
} else if (hookEvent === "Stop" && whisperKey && dedupState.stop_turn_by_session[whisperKey]) {
|
|
2205
|
+
dedupState.stop_turn_by_session[whisperKey].awaiting_stop_retry = false;
|
|
2003
2206
|
}
|
|
2004
2207
|
telem.pending_raw_tokens_delta = 0;
|
|
2005
2208
|
telem.pending_dropped_tokens_delta = 0;
|
|
@@ -3567,6 +3770,13 @@ if (parsed.isStatus) {
|
|
|
3567
3770
|
return;
|
|
3568
3771
|
}
|
|
3569
3772
|
|
|
3773
|
+
if (parsed.isHookDaemon) {
|
|
3774
|
+
runHookDaemonServer()
|
|
3775
|
+
.then(() => {})
|
|
3776
|
+
.catch(() => process.exit(1));
|
|
3777
|
+
return;
|
|
3778
|
+
}
|
|
3779
|
+
|
|
3570
3780
|
if (parsed.isHook) {
|
|
3571
3781
|
runAmbientHookMode(parsed)
|
|
3572
3782
|
.then(() => process.exit(process.exitCode || 0))
|
|
@@ -3757,6 +3967,420 @@ const CODE_MODE_TOOLS = [
|
|
|
3757
3967
|
},
|
|
3758
3968
|
];
|
|
3759
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
|
+
|
|
3760
4384
|
async function apiRequest(opts, method, urlPath, body) {
|
|
3761
4385
|
if (!opts.apiKey) {
|
|
3762
4386
|
throw new Error(
|
package/dist/index.js
CHANGED
|
@@ -303,7 +303,7 @@ class MemoryClient {
|
|
|
303
303
|
const headers = {
|
|
304
304
|
Accept: "application/json",
|
|
305
305
|
"Content-Type": "application/json",
|
|
306
|
-
"User-Agent": "slashml-memory-ts/1.0.
|
|
306
|
+
"User-Agent": "slashml-memory-ts/1.0.15",
|
|
307
307
|
};
|
|
308
308
|
if (this.apiKey) {
|
|
309
309
|
headers.Authorization = `Bearer ${this.apiKey}`;
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -605,7 +605,7 @@ export class MemoryClient {
|
|
|
605
605
|
const headers: Record<string, string> = {
|
|
606
606
|
Accept: "application/json",
|
|
607
607
|
"Content-Type": "application/json",
|
|
608
|
-
"User-Agent": "slashml-memory-ts/1.0.
|
|
608
|
+
"User-Agent": "slashml-memory-ts/1.0.15",
|
|
609
609
|
};
|
|
610
610
|
if (this.apiKey) {
|
|
611
611
|
headers.Authorization = `Bearer ${this.apiKey}`;
|