@slashml/memory 1.0.8 → 1.0.9
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 +879 -8
- package/dist/index.d.ts +347 -233
- package/dist/index.js +824 -624
- package/dist/index.mjs +25 -629
- package/package.json +2 -1
- package/src/index.ts +366 -11
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.9";
|
|
14
14
|
|
|
15
15
|
function printHelp() {
|
|
16
16
|
console.log(`@slashml/memory v${PACKAGE_VERSION} -- Official CLI & MCP Stdio Server for / ml (SlashML · https://slashml.ai)
|
|
@@ -37,8 +37,13 @@ Options:
|
|
|
37
37
|
--write-env Save SLASHML_API_KEY to .env in the current directory
|
|
38
38
|
--hook Run as an ambient IDE/agent lifecycle hook (reads hook JSON from stdin)
|
|
39
39
|
--install-hooks Register ambient / ml hooks in ~/.claude/settings.json & .cursor/hooks.json
|
|
40
|
+
sync-rules, --sync-rules Sync active / ml project rules into CLAUDE.md and AGENTS.md (for cloud sandboxes)
|
|
41
|
+
watch-sandbox, --watch-sandbox Tail live sandbox transcripts to assimilate rules and inject mid-turn course corrections
|
|
42
|
+
--daemon Run watch-sandbox as a detached background process (exits 0 immediately)
|
|
43
|
+
--once Run a single watch-sandbox transcript scan pass and exit
|
|
44
|
+
--transcript-dir <dir> Additional directory to scan for .jsonl agent transcripts
|
|
40
45
|
status, --status Show ambient memory ROI telemetry (tokens processed, % noise filtered, rules assimilated, amnesia intercepted)
|
|
41
|
-
--json Format status output as JSON
|
|
46
|
+
--json Format status/sync output as JSON
|
|
42
47
|
--signup <work-email> Request a 6-digit OTP to provision a / ml free API key (requires work/custom domain @company.com; for @gmail.com / @hotmail.com sign in with Google/GitHub at https://app.slashml.ai)
|
|
43
48
|
--verify <work-email> <code> Verify 6-digit code and print the new SLASHML_API_KEY to stdout`);
|
|
44
49
|
}
|
|
@@ -183,6 +188,13 @@ function parseCliArgs(argv) {
|
|
|
183
188
|
let isInstallHooks = false;
|
|
184
189
|
let isStatus = false;
|
|
185
190
|
let jsonOutput = false;
|
|
191
|
+
let isSyncRules = false;
|
|
192
|
+
let isWatchSandbox = false;
|
|
193
|
+
let isDaemon = false;
|
|
194
|
+
let isOnce = false;
|
|
195
|
+
let intervalMs = 1500;
|
|
196
|
+
let transcriptDir = process.env.SLASHML_TRANSCRIPT_DIR || null;
|
|
197
|
+
let forgetId = null;
|
|
186
198
|
|
|
187
199
|
for (let i = 0; i < argv.length; i++) {
|
|
188
200
|
const arg = argv[i];
|
|
@@ -198,6 +210,20 @@ function parseCliArgs(argv) {
|
|
|
198
210
|
hookEvent = argv[++i];
|
|
199
211
|
} else if (arg === "--install-hooks" || arg === "install-hooks") {
|
|
200
212
|
isInstallHooks = true;
|
|
213
|
+
} else if (arg === "--sync-rules" || arg === "sync-rules") {
|
|
214
|
+
isSyncRules = true;
|
|
215
|
+
} else if (arg === "--watch-sandbox" || arg === "watch-sandbox") {
|
|
216
|
+
isWatchSandbox = true;
|
|
217
|
+
} else if ((arg === "--forget" || arg === "forget") && i + 1 < argv.length) {
|
|
218
|
+
forgetId = argv[++i];
|
|
219
|
+
} else if (arg === "--daemon") {
|
|
220
|
+
isDaemon = true;
|
|
221
|
+
} else if (arg === "--once") {
|
|
222
|
+
isOnce = true;
|
|
223
|
+
} else if (arg === "--interval-ms" && i + 1 < argv.length) {
|
|
224
|
+
intervalMs = Math.max(250, Number(argv[++i]) || 1500);
|
|
225
|
+
} else if (arg === "--transcript-dir" && i + 1 < argv.length) {
|
|
226
|
+
transcriptDir = argv[++i];
|
|
201
227
|
} else if (arg === "--status" || arg === "status") {
|
|
202
228
|
isStatus = true;
|
|
203
229
|
} else if (arg === "--json") {
|
|
@@ -258,6 +284,13 @@ function parseCliArgs(argv) {
|
|
|
258
284
|
isInstallHooks,
|
|
259
285
|
isStatus,
|
|
260
286
|
jsonOutput,
|
|
287
|
+
isSyncRules,
|
|
288
|
+
isWatchSandbox,
|
|
289
|
+
isDaemon,
|
|
290
|
+
isOnce,
|
|
291
|
+
intervalMs,
|
|
292
|
+
transcriptDir,
|
|
293
|
+
forgetId,
|
|
261
294
|
};
|
|
262
295
|
}
|
|
263
296
|
|
|
@@ -1301,11 +1334,684 @@ async function runAmbientHookMode(opts) {
|
|
|
1301
1334
|
}
|
|
1302
1335
|
}
|
|
1303
1336
|
|
|
1337
|
+
const SANDBOX_INTERVENTION_PATH =
|
|
1338
|
+
process.env.SLASHML_SANDBOX_INTERVENTION_PATH || "/tmp/slashml-sandbox-intervention.json";
|
|
1339
|
+
const SANDBOX_OFFSETS_PATH =
|
|
1340
|
+
process.env.SLASHML_SANDBOX_OFFSETS_PATH || "/tmp/slashml-sandbox-offsets.json";
|
|
1341
|
+
const SANDBOX_PID_PATH =
|
|
1342
|
+
process.env.SLASHML_SANDBOX_PID_PATH || "/tmp/slashml-watch-sandbox.pid";
|
|
1343
|
+
|
|
1344
|
+
function resolveSandboxTargets(explicitRepo) {
|
|
1345
|
+
if (explicitRepo && String(explicitRepo).trim()) {
|
|
1346
|
+
return [path.resolve(String(explicitRepo).trim())];
|
|
1347
|
+
}
|
|
1348
|
+
const cwd = process.cwd();
|
|
1349
|
+
const targets = new Set();
|
|
1350
|
+
const repoIndicators = [".git", ".ellipsis", "CLAUDE.md", "AGENTS.md", "package.json", "pyproject.toml"];
|
|
1351
|
+
if (repoIndicators.some((f) => fs.existsSync(path.join(cwd, f)))) {
|
|
1352
|
+
targets.add(cwd);
|
|
1353
|
+
}
|
|
1354
|
+
try {
|
|
1355
|
+
const entries = fs.readdirSync(cwd, { withFileTypes: true });
|
|
1356
|
+
let subCount = 0;
|
|
1357
|
+
for (const entry of entries) {
|
|
1358
|
+
if (subCount >= 6) break;
|
|
1359
|
+
if (!entry.isDirectory() || entry.name.startsWith(".") || entry.name === "node_modules") continue;
|
|
1360
|
+
const subPath = path.join(cwd, entry.name);
|
|
1361
|
+
if (repoIndicators.some((f) => fs.existsSync(path.join(subPath, f)))) {
|
|
1362
|
+
targets.add(subPath);
|
|
1363
|
+
subCount += 1;
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
} catch {
|
|
1367
|
+
// ignore directory scan errors
|
|
1368
|
+
}
|
|
1369
|
+
if (targets.size === 0) {
|
|
1370
|
+
targets.add(cwd);
|
|
1371
|
+
}
|
|
1372
|
+
return Array.from(targets);
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
function upsertAmbientMarkdownSection(filePath, sectionBody) {
|
|
1376
|
+
const startMarker = "<!-- SLASHML-AMBIENT-MEMORY:START -->";
|
|
1377
|
+
const endMarker = "<!-- SLASHML-AMBIENT-MEMORY:END -->";
|
|
1378
|
+
const block = `${startMarker}\n${sectionBody.trim()}\n${endMarker}`;
|
|
1379
|
+
let existing = "";
|
|
1380
|
+
if (fs.existsSync(filePath)) {
|
|
1381
|
+
try {
|
|
1382
|
+
existing = fs.readFileSync(filePath, "utf8");
|
|
1383
|
+
} catch {
|
|
1384
|
+
existing = "";
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
const startIdx = existing.indexOf(startMarker);
|
|
1388
|
+
const endIdx = existing.indexOf(endMarker);
|
|
1389
|
+
let updated = "";
|
|
1390
|
+
if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
|
|
1391
|
+
updated =
|
|
1392
|
+
existing.slice(0, startIdx).replace(/\n*$/, "\n\n") +
|
|
1393
|
+
block +
|
|
1394
|
+
"\n" +
|
|
1395
|
+
existing.slice(endIdx + endMarker.length).replace(/^\n*/, "");
|
|
1396
|
+
} else if (existing.trim()) {
|
|
1397
|
+
updated = `${existing.replace(/\n*$/, "")}\n\n${block}\n`;
|
|
1398
|
+
} else {
|
|
1399
|
+
updated = `${block}\n`;
|
|
1400
|
+
}
|
|
1401
|
+
fs.writeFileSync(filePath, updated.replace(/^\n+/, ""), "utf8");
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
async function runSyncRulesCommand(opts) {
|
|
1405
|
+
const targets = resolveSandboxTargets(opts.repo);
|
|
1406
|
+
const primaryDir = targets[0] || process.cwd();
|
|
1407
|
+
const projectId =
|
|
1408
|
+
process.env.SLASHML_PROJECT_ID || path.basename(primaryDir.replace(/[\\/]+$/, "")) || "default";
|
|
1409
|
+
|
|
1410
|
+
if (!opts.apiKey) {
|
|
1411
|
+
if (!opts.silent) {
|
|
1412
|
+
const msg = {
|
|
1413
|
+
status: "skipped",
|
|
1414
|
+
reason: "SLASHML_API_KEY not set",
|
|
1415
|
+
targets,
|
|
1416
|
+
};
|
|
1417
|
+
if (opts.jsonOutput) {
|
|
1418
|
+
process.stdout.write(JSON.stringify(msg, null, 2) + "\n");
|
|
1419
|
+
} else {
|
|
1420
|
+
console.log("[/ ml] SLASHML_API_KEY not set; skipping sync-rules.");
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
return { synced_count: 0, targets };
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
const memories = [];
|
|
1427
|
+
const seenText = new Set();
|
|
1428
|
+
|
|
1429
|
+
try {
|
|
1430
|
+
const targetUserId = opts.userId || "default";
|
|
1431
|
+
const q = new URLSearchParams({
|
|
1432
|
+
user_id: targetUserId,
|
|
1433
|
+
limit: "200",
|
|
1434
|
+
include_code: "false",
|
|
1435
|
+
});
|
|
1436
|
+
const listResp = await apiRequest(opts, "GET", `/v1/memories?${q.toString()}`);
|
|
1437
|
+
const rawItems = Array.isArray(listResp)
|
|
1438
|
+
? listResp
|
|
1439
|
+
: Array.isArray(listResp?.results)
|
|
1440
|
+
? listResp.results
|
|
1441
|
+
: Array.isArray(listResp?.memories)
|
|
1442
|
+
? listResp.memories
|
|
1443
|
+
: [];
|
|
1444
|
+
const reversedItems = rawItems.slice().reverse();
|
|
1445
|
+
const orderedItems = [
|
|
1446
|
+
...reversedItems.filter((item) => item && item.user_id === targetUserId),
|
|
1447
|
+
...reversedItems.filter((item) => item && item.user_id !== targetUserId),
|
|
1448
|
+
];
|
|
1449
|
+
for (const item of orderedItems) {
|
|
1450
|
+
if (!item || typeof item !== "object") continue;
|
|
1451
|
+
const meta = item.metadata && typeof item.metadata === "object" ? item.metadata : {};
|
|
1452
|
+
if (meta.kind === "code_symbol" || meta.modality === "code") continue;
|
|
1453
|
+
const text = String(item.memory || item.text || item.content || "").trim();
|
|
1454
|
+
if (!text || text.startsWith("[FILE] ")) continue;
|
|
1455
|
+
const norm = text.toLowerCase();
|
|
1456
|
+
if (seenText.has(norm)) continue;
|
|
1457
|
+
seenText.add(norm);
|
|
1458
|
+
memories.push({
|
|
1459
|
+
id: String(item.id || item.memory_id || `mem_${memories.length + 1}`),
|
|
1460
|
+
user_id: item.user_id || null,
|
|
1461
|
+
text,
|
|
1462
|
+
});
|
|
1463
|
+
}
|
|
1464
|
+
} catch {
|
|
1465
|
+
// Fail-open if listing memories fails
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
let activeIntervention = opts.activeIntervention || "";
|
|
1469
|
+
if (!activeIntervention && fs.existsSync(SANDBOX_INTERVENTION_PATH)) {
|
|
1470
|
+
try {
|
|
1471
|
+
const saved = JSON.parse(fs.readFileSync(SANDBOX_INTERVENTION_PATH, "utf8"));
|
|
1472
|
+
if (saved && saved.intervention_message && Date.now() - Number(saved.timestamp || 0) < 600000) {
|
|
1473
|
+
activeIntervention = String(saved.intervention_message);
|
|
1474
|
+
}
|
|
1475
|
+
} catch {
|
|
1476
|
+
// ignore
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
const lines = [
|
|
1481
|
+
"## / ml Ambient Project Memory (Auto-Synced)",
|
|
1482
|
+
"",
|
|
1483
|
+
"The following architectural rules, project invariants, and PR review corrections are persisted across ephemeral sandbox sessions by `/ ml` (`https://slashml.ai`). Follow them strictly:",
|
|
1484
|
+
"",
|
|
1485
|
+
];
|
|
1486
|
+
if (activeIntervention) {
|
|
1487
|
+
lines.push("> [!CAUTION]");
|
|
1488
|
+
lines.push("> **ACTIVE / ml MID-TURN COURSE CORRECTION:**");
|
|
1489
|
+
for (const l of activeIntervention.split(/\r?\n/)) {
|
|
1490
|
+
lines.push(`> ${l}`);
|
|
1491
|
+
}
|
|
1492
|
+
lines.push("");
|
|
1493
|
+
}
|
|
1494
|
+
if (memories.length === 0) {
|
|
1495
|
+
lines.push("- *(No project rules recorded yet for this workspace namespace. New rules and PR review corrections will be assimilated automatically during this session.)*");
|
|
1496
|
+
} else {
|
|
1497
|
+
for (const m of memories.slice(0, 20)) {
|
|
1498
|
+
lines.push(`- **[${m.id}]** ${m.text}`);
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
const sectionBody = lines.join("\n");
|
|
1503
|
+
const updatedFiles = [];
|
|
1504
|
+
for (const dir of targets) {
|
|
1505
|
+
for (const fname of ["CLAUDE.md", "AGENTS.md"]) {
|
|
1506
|
+
const fpath = path.join(dir, fname);
|
|
1507
|
+
try {
|
|
1508
|
+
upsertAmbientMarkdownSection(fpath, sectionBody);
|
|
1509
|
+
updatedFiles.push(fpath);
|
|
1510
|
+
} catch {
|
|
1511
|
+
// ignore unwritable paths
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
const result = {
|
|
1517
|
+
status: "synced",
|
|
1518
|
+
project_id: projectId,
|
|
1519
|
+
user_id: opts.userId || "default",
|
|
1520
|
+
synced_count: memories.length,
|
|
1521
|
+
memories,
|
|
1522
|
+
active_intervention: Boolean(activeIntervention),
|
|
1523
|
+
updated_files: updatedFiles,
|
|
1524
|
+
};
|
|
1525
|
+
if (!opts.silent) {
|
|
1526
|
+
if (opts.jsonOutput) {
|
|
1527
|
+
process.stdout.write(JSON.stringify(result, null, 2) + "\n");
|
|
1528
|
+
} else {
|
|
1529
|
+
console.log(
|
|
1530
|
+
`[/ ml] Synced ${memories.length} project memories into ${updatedFiles.length} workspace file(s) (${targets.join(", ")}).`
|
|
1531
|
+
);
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
return result;
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
function collectSandboxTranscriptFiles(extraDir) {
|
|
1538
|
+
const roots = [];
|
|
1539
|
+
const onlyExplicitDir = Boolean(extraDir && String(extraDir).trim());
|
|
1540
|
+
if (onlyExplicitDir) {
|
|
1541
|
+
roots.push(path.resolve(String(extraDir).trim()));
|
|
1542
|
+
} else {
|
|
1543
|
+
const home = os.homedir();
|
|
1544
|
+
roots.push(
|
|
1545
|
+
path.join(home, ".claude", "projects"),
|
|
1546
|
+
path.join(home, ".codex", "sessions"),
|
|
1547
|
+
"/tmp/slashml-transcripts"
|
|
1548
|
+
);
|
|
1549
|
+
}
|
|
1550
|
+
const nowMs = Date.now();
|
|
1551
|
+
const maxAgeMs = 30 * 60 * 1000;
|
|
1552
|
+
const found = [];
|
|
1553
|
+
function walk(dir, depth = 0) {
|
|
1554
|
+
if (depth > 5 || !fs.existsSync(dir)) return;
|
|
1555
|
+
let entries = [];
|
|
1556
|
+
try {
|
|
1557
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
1558
|
+
} catch {
|
|
1559
|
+
return;
|
|
1560
|
+
}
|
|
1561
|
+
for (const e of entries) {
|
|
1562
|
+
const full = path.join(dir, e.name);
|
|
1563
|
+
if (e.isDirectory()) {
|
|
1564
|
+
walk(full, depth + 1);
|
|
1565
|
+
} else if (e.isFile() && e.name.endsWith(".jsonl")) {
|
|
1566
|
+
if (!onlyExplicitDir) {
|
|
1567
|
+
try {
|
|
1568
|
+
const st = fs.statSync(full);
|
|
1569
|
+
if (nowMs - st.mtimeMs > maxAgeMs) continue;
|
|
1570
|
+
} catch {
|
|
1571
|
+
continue;
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
found.push(full);
|
|
1575
|
+
}
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
for (const r of roots) {
|
|
1579
|
+
walk(r, 0);
|
|
1580
|
+
}
|
|
1581
|
+
return found;
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
function extractEventsFromTranscriptEntry(entry) {
|
|
1585
|
+
const events = [];
|
|
1586
|
+
if (!entry || typeof entry !== "object") return events;
|
|
1587
|
+
|
|
1588
|
+
if (entry.hook_event_name || entry.hookEventName) {
|
|
1589
|
+
events.push({
|
|
1590
|
+
hook_event_name: String(entry.hook_event_name || entry.hookEventName),
|
|
1591
|
+
text: String(entry.text || entry.prompt || ""),
|
|
1592
|
+
prompt: String(entry.prompt || entry.text || ""),
|
|
1593
|
+
tool_name: entry.tool_name || entry.toolName || null,
|
|
1594
|
+
tool_input: entry.tool_input || entry.toolInput || null,
|
|
1595
|
+
});
|
|
1596
|
+
return events;
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
const msg = entry.message && typeof entry.message === "object" ? entry.message : entry;
|
|
1600
|
+
const role = String(msg.role || entry.type || "").toLowerCase();
|
|
1601
|
+
|
|
1602
|
+
if (role === "user" || entry.type === "USER_INPUT") {
|
|
1603
|
+
let text = "";
|
|
1604
|
+
if (typeof msg.content === "string") {
|
|
1605
|
+
text = msg.content;
|
|
1606
|
+
} else if (typeof entry.content === "string") {
|
|
1607
|
+
text = entry.content;
|
|
1608
|
+
} else if (Array.isArray(msg.content)) {
|
|
1609
|
+
text = msg.content
|
|
1610
|
+
.filter((b) => b && (b.type === "text" || typeof b.text === "string"))
|
|
1611
|
+
.map((b) => String(b.text || ""))
|
|
1612
|
+
.join("\n");
|
|
1613
|
+
}
|
|
1614
|
+
if (text && text.trim()) {
|
|
1615
|
+
events.push({
|
|
1616
|
+
hook_event_name: "UserPromptSubmit",
|
|
1617
|
+
text: text.trim(),
|
|
1618
|
+
prompt: text.trim(),
|
|
1619
|
+
tool_name: null,
|
|
1620
|
+
tool_input: null,
|
|
1621
|
+
});
|
|
1622
|
+
}
|
|
1623
|
+
return events;
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
if (role === "assistant" || entry.type === "PLANNER_RESPONSE") {
|
|
1627
|
+
const textParts = [];
|
|
1628
|
+
if (typeof msg.content === "string" && msg.content.trim()) {
|
|
1629
|
+
textParts.push(msg.content.trim());
|
|
1630
|
+
} else if (typeof entry.content === "string" && entry.content.trim()) {
|
|
1631
|
+
textParts.push(entry.content.trim());
|
|
1632
|
+
} else if (Array.isArray(msg.content)) {
|
|
1633
|
+
for (const b of msg.content) {
|
|
1634
|
+
if (!b || typeof b !== "object") continue;
|
|
1635
|
+
if (b.type === "text" && typeof b.text === "string" && b.text.trim()) {
|
|
1636
|
+
textParts.push(b.text.trim());
|
|
1637
|
+
} else if (b.type === "tool_use" && b.name) {
|
|
1638
|
+
const toolIn = b.input && typeof b.input === "object" ? b.input : {};
|
|
1639
|
+
const toolSummary =
|
|
1640
|
+
toolIn.command ||
|
|
1641
|
+
toolIn.CommandLine ||
|
|
1642
|
+
toolIn.content ||
|
|
1643
|
+
toolIn.Content ||
|
|
1644
|
+
toolIn.new_string ||
|
|
1645
|
+
toolIn.Replacement ||
|
|
1646
|
+
JSON.stringify(toolIn);
|
|
1647
|
+
events.push({
|
|
1648
|
+
hook_event_name: "PreToolUse",
|
|
1649
|
+
text: String(toolSummary || ""),
|
|
1650
|
+
tool_name: String(b.name),
|
|
1651
|
+
tool_input: toolIn,
|
|
1652
|
+
});
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
if (Array.isArray(entry.tool_calls)) {
|
|
1657
|
+
for (const tc of entry.tool_calls) {
|
|
1658
|
+
if (!tc || typeof tc !== "object") continue;
|
|
1659
|
+
const name = tc.name || (tc.function && tc.function.name);
|
|
1660
|
+
const toolIn = tc.args || tc.arguments || tc.input || (tc.function && tc.function.arguments) || {};
|
|
1661
|
+
if (name) {
|
|
1662
|
+
const parsedIn =
|
|
1663
|
+
typeof toolIn === "string"
|
|
1664
|
+
? (() => {
|
|
1665
|
+
try {
|
|
1666
|
+
return JSON.parse(toolIn);
|
|
1667
|
+
} catch {
|
|
1668
|
+
return { raw: toolIn };
|
|
1669
|
+
}
|
|
1670
|
+
})()
|
|
1671
|
+
: toolIn;
|
|
1672
|
+
const toolSummary =
|
|
1673
|
+
parsedIn.command ||
|
|
1674
|
+
parsedIn.CommandLine ||
|
|
1675
|
+
parsedIn.content ||
|
|
1676
|
+
parsedIn.Content ||
|
|
1677
|
+
parsedIn.new_string ||
|
|
1678
|
+
parsedIn.Replacement ||
|
|
1679
|
+
JSON.stringify(parsedIn);
|
|
1680
|
+
events.push({
|
|
1681
|
+
hook_event_name: "PreToolUse",
|
|
1682
|
+
text: String(toolSummary || ""),
|
|
1683
|
+
tool_name: String(name),
|
|
1684
|
+
tool_input: parsedIn,
|
|
1685
|
+
});
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
if (textParts.length > 0) {
|
|
1690
|
+
events.push({
|
|
1691
|
+
hook_event_name: "Stop",
|
|
1692
|
+
text: textParts.join("\n"),
|
|
1693
|
+
tool_name: null,
|
|
1694
|
+
tool_input: null,
|
|
1695
|
+
});
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
return events;
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
async function scanSandboxTranscriptsOnce(opts, state) {
|
|
1702
|
+
state.whisperedBySession = state.whisperedBySession || {};
|
|
1703
|
+
const files = collectSandboxTranscriptFiles(opts.transcriptDir);
|
|
1704
|
+
const targets = resolveSandboxTargets(opts.repo);
|
|
1705
|
+
const primaryDir = targets[0] || process.cwd();
|
|
1706
|
+
const projectId =
|
|
1707
|
+
process.env.SLASHML_PROJECT_ID || path.basename(primaryDir.replace(/[\\/]+$/, "")) || "default";
|
|
1708
|
+
|
|
1709
|
+
let processedEvents = 0;
|
|
1710
|
+
let assimilatedCount = 0;
|
|
1711
|
+
let intervenedCount = 0;
|
|
1712
|
+
const interventions = [];
|
|
1713
|
+
|
|
1714
|
+
for (const filePath of files) {
|
|
1715
|
+
let stat = null;
|
|
1716
|
+
try {
|
|
1717
|
+
stat = fs.statSync(filePath);
|
|
1718
|
+
} catch {
|
|
1719
|
+
continue;
|
|
1720
|
+
}
|
|
1721
|
+
const prevOffset = Number(state.offsets[filePath] || 0);
|
|
1722
|
+
const startOffset = stat.size < prevOffset ? 0 : prevOffset;
|
|
1723
|
+
if (stat.size <= startOffset) continue;
|
|
1724
|
+
|
|
1725
|
+
const len = stat.size - startOffset;
|
|
1726
|
+
const fd = fs.openSync(filePath, "r");
|
|
1727
|
+
const buf = Buffer.alloc(len);
|
|
1728
|
+
fs.readSync(fd, buf, 0, len, startOffset);
|
|
1729
|
+
fs.closeSync(fd);
|
|
1730
|
+
|
|
1731
|
+
const chunkStr = buf.toString("utf8");
|
|
1732
|
+
const lastNewline = chunkStr.lastIndexOf("\n");
|
|
1733
|
+
if (lastNewline === -1) continue;
|
|
1734
|
+
|
|
1735
|
+
const completeStr = chunkStr.slice(0, lastNewline + 1);
|
|
1736
|
+
state.offsets[filePath] = startOffset + Buffer.byteLength(completeStr, "utf8");
|
|
1737
|
+
|
|
1738
|
+
const sessionId = path.basename(filePath, ".jsonl");
|
|
1739
|
+
const lines = completeStr.split(/\r?\n/);
|
|
1740
|
+
for (const rawLine of lines) {
|
|
1741
|
+
const line = rawLine.trim();
|
|
1742
|
+
if (!line || !line.startsWith("{")) continue;
|
|
1743
|
+
let entry = null;
|
|
1744
|
+
try {
|
|
1745
|
+
entry = JSON.parse(line);
|
|
1746
|
+
} catch {
|
|
1747
|
+
continue;
|
|
1748
|
+
}
|
|
1749
|
+
const evList = extractEventsFromTranscriptEntry(entry);
|
|
1750
|
+
for (const ev of evList) {
|
|
1751
|
+
if (ev.hook_event_name === "UserPromptSubmit" && ev.prompt) {
|
|
1752
|
+
state.lastPromptBySession[sessionId] = ev.prompt;
|
|
1753
|
+
}
|
|
1754
|
+
if (
|
|
1755
|
+
ev.hook_event_name === "PreToolUse" &&
|
|
1756
|
+
ev.tool_name &&
|
|
1757
|
+
HOOK_READ_ONLY_TOOLS.has(String(ev.tool_name).toLowerCase())
|
|
1758
|
+
) {
|
|
1759
|
+
recordLocalHookDrop(estimateTokens(ev.text));
|
|
1760
|
+
continue;
|
|
1761
|
+
}
|
|
1762
|
+
const deltaText = String(ev.text || "").trim().slice(0, 1024);
|
|
1763
|
+
if (!deltaText || deltaText.length < 4) continue;
|
|
1764
|
+
if (!opts.apiKey) continue;
|
|
1765
|
+
|
|
1766
|
+
const promptContext = state.lastPromptBySession[sessionId] || deltaText;
|
|
1767
|
+
const rawTok = estimateTokens(deltaText);
|
|
1768
|
+
const telem = loadHookTelemetry();
|
|
1769
|
+
|
|
1770
|
+
try {
|
|
1771
|
+
const sessionWhispered = Array.isArray(state.whisperedBySession[sessionId])
|
|
1772
|
+
? state.whisperedBySession[sessionId]
|
|
1773
|
+
: [];
|
|
1774
|
+
const resp = await apiRequest(opts, "POST", "/v1/memory/intervene", {
|
|
1775
|
+
hook_event_name: ev.hook_event_name,
|
|
1776
|
+
prompt: promptContext,
|
|
1777
|
+
text: deltaText,
|
|
1778
|
+
...(ev.hook_event_name === "Stop" ? { last_assistant_message: deltaText } : {}),
|
|
1779
|
+
...(ev.hook_event_name !== "UserPromptSubmit" && sessionWhispered.length > 0
|
|
1780
|
+
? { whispered_memory_ids: sessionWhispered }
|
|
1781
|
+
: {}),
|
|
1782
|
+
tool_name: ev.tool_name || null,
|
|
1783
|
+
tool_input: ev.tool_input || null,
|
|
1784
|
+
commit_writes: true,
|
|
1785
|
+
user_id: opts.userId || "default",
|
|
1786
|
+
project_id: projectId,
|
|
1787
|
+
session_id: sessionId,
|
|
1788
|
+
});
|
|
1789
|
+
processedEvents += 1;
|
|
1790
|
+
telem.conversation_tokens_processed = (telem.conversation_tokens_processed || 0) + rawTok;
|
|
1791
|
+
telem.events_processed = (telem.events_processed || 0) + 1;
|
|
1792
|
+
|
|
1793
|
+
if (ev.hook_event_name === "UserPromptSubmit" && resp && resp.should_intervene) {
|
|
1794
|
+
const recalledIds =
|
|
1795
|
+
Array.isArray(resp.violated_memory_ids) && resp.violated_memory_ids.length > 0
|
|
1796
|
+
? resp.violated_memory_ids
|
|
1797
|
+
: resp.triggered_memory_id
|
|
1798
|
+
? [resp.triggered_memory_id]
|
|
1799
|
+
: [];
|
|
1800
|
+
if (recalledIds.length > 0) {
|
|
1801
|
+
state.whisperedBySession[sessionId] = recalledIds;
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
const isMidTurnBlock =
|
|
1806
|
+
ev.hook_event_name !== "UserPromptSubmit" &&
|
|
1807
|
+
Boolean(resp && resp.should_intervene && resp.intervention_message);
|
|
1808
|
+
|
|
1809
|
+
if (resp && (resp.should_write || isMidTurnBlock)) {
|
|
1810
|
+
const spanTok = estimateTokens(resp.extracted_write_span || deltaText);
|
|
1811
|
+
telem.noise_tokens_filtered =
|
|
1812
|
+
(telem.noise_tokens_filtered || 0) + Math.max(0, rawTok - spanTok);
|
|
1813
|
+
if (resp.should_write) {
|
|
1814
|
+
assimilatedCount += 1;
|
|
1815
|
+
telem.memories_assimilated = (telem.memories_assimilated || 0) + 1;
|
|
1816
|
+
if (resp.write_novelty_action === "SUPERSEDES") {
|
|
1817
|
+
telem.memories_superseded = (telem.memories_superseded || 0) + 1;
|
|
1818
|
+
}
|
|
1819
|
+
await runSyncRulesCommand({ ...opts, silent: true });
|
|
1820
|
+
}
|
|
1821
|
+
if (isMidTurnBlock) {
|
|
1822
|
+
intervenedCount += 1;
|
|
1823
|
+
telem.amnesia_episodes_intercepted = (telem.amnesia_episodes_intercepted || 0) + 1;
|
|
1824
|
+
const interventionRecord = {
|
|
1825
|
+
timestamp: Date.now(),
|
|
1826
|
+
session_id: sessionId,
|
|
1827
|
+
severity: resp.intervention_severity || "BLOCK",
|
|
1828
|
+
intervention_message: resp.intervention_message,
|
|
1829
|
+
violated_memory_ids: resp.violated_memory_ids || [],
|
|
1830
|
+
};
|
|
1831
|
+
interventions.push(interventionRecord);
|
|
1832
|
+
await runSyncRulesCommand({
|
|
1833
|
+
...opts,
|
|
1834
|
+
silent: true,
|
|
1835
|
+
activeIntervention: resp.intervention_message,
|
|
1836
|
+
});
|
|
1837
|
+
try {
|
|
1838
|
+
fs.writeFileSync(
|
|
1839
|
+
SANDBOX_INTERVENTION_PATH,
|
|
1840
|
+
JSON.stringify(interventionRecord, null, 2) + "\n",
|
|
1841
|
+
"utf8"
|
|
1842
|
+
);
|
|
1843
|
+
} catch {
|
|
1844
|
+
// ignore
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
const ellipsisSessionId = process.env.ELLIPSIS_SESSION_ID;
|
|
1848
|
+
const ellipsisToken =
|
|
1849
|
+
process.env.ELLIPSIS_API_TOKEN || process.env.ELLIPSIS_SESSION_TOKEN;
|
|
1850
|
+
const ellipsisBase = (
|
|
1851
|
+
process.env.ELLIPSIS_API_URL || "https://api.ellipsis.dev"
|
|
1852
|
+
).replace(/\/+$/, "");
|
|
1853
|
+
if (ellipsisSessionId && ellipsisToken && !state.notifiedSessions[sessionId]) {
|
|
1854
|
+
state.notifiedSessions[sessionId] = true;
|
|
1855
|
+
try {
|
|
1856
|
+
await fetch(`${ellipsisBase}/v1/sessions/${ellipsisSessionId}/messages`, {
|
|
1857
|
+
method: "POST",
|
|
1858
|
+
headers: {
|
|
1859
|
+
Authorization: `Bearer ${ellipsisToken}`,
|
|
1860
|
+
"Content-Type": "application/json",
|
|
1861
|
+
},
|
|
1862
|
+
body: JSON.stringify({
|
|
1863
|
+
message: resp.intervention_message,
|
|
1864
|
+
}),
|
|
1865
|
+
});
|
|
1866
|
+
} catch {
|
|
1867
|
+
// fail-open if session follow-up API is not reachable
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
} else {
|
|
1872
|
+
telem.noise_tokens_filtered = (telem.noise_tokens_filtered || 0) + rawTok;
|
|
1873
|
+
telem.events_filtered_noise = (telem.events_filtered_noise || 0) + 1;
|
|
1874
|
+
}
|
|
1875
|
+
saveHookTelemetry(telem);
|
|
1876
|
+
} catch {
|
|
1877
|
+
// fail-open on transient API error
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
|
|
1883
|
+
try {
|
|
1884
|
+
fs.writeFileSync(SANDBOX_OFFSETS_PATH, JSON.stringify(state, null, 2) + "\n", "utf8");
|
|
1885
|
+
} catch {
|
|
1886
|
+
// ignore offset persistence error
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
return {
|
|
1890
|
+
scanned_files: files.length,
|
|
1891
|
+
processed_events: processedEvents,
|
|
1892
|
+
memories_assimilated: assimilatedCount,
|
|
1893
|
+
interventions_triggered: intervenedCount,
|
|
1894
|
+
interventions,
|
|
1895
|
+
};
|
|
1896
|
+
}
|
|
1897
|
+
|
|
1898
|
+
async function runWatchSandboxCommand(opts) {
|
|
1899
|
+
if (opts.isDaemon) {
|
|
1900
|
+
const { spawn } = require("child_process");
|
|
1901
|
+
const forwarded = process.argv
|
|
1902
|
+
.slice(2)
|
|
1903
|
+
.filter((a) => a !== "--daemon");
|
|
1904
|
+
const child = spawn(process.execPath, [__filename, ...forwarded], {
|
|
1905
|
+
detached: true,
|
|
1906
|
+
stdio: "ignore",
|
|
1907
|
+
env: process.env,
|
|
1908
|
+
});
|
|
1909
|
+
child.unref();
|
|
1910
|
+
try {
|
|
1911
|
+
fs.writeFileSync(SANDBOX_PID_PATH, String(child.pid) + "\n", "utf8");
|
|
1912
|
+
} catch {
|
|
1913
|
+
// ignore
|
|
1914
|
+
}
|
|
1915
|
+
if (opts.jsonOutput) {
|
|
1916
|
+
process.stdout.write(
|
|
1917
|
+
JSON.stringify({ status: "daemon_started", pid: child.pid }, null, 2) + "\n"
|
|
1918
|
+
);
|
|
1919
|
+
} else {
|
|
1920
|
+
console.log(`[/ ml] Started watch-sandbox background daemon (PID ${child.pid}).`);
|
|
1921
|
+
}
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
let state = {
|
|
1926
|
+
offsets: {},
|
|
1927
|
+
lastPromptBySession: {},
|
|
1928
|
+
whisperedBySession: {},
|
|
1929
|
+
notifiedSessions: {},
|
|
1930
|
+
};
|
|
1931
|
+
if (fs.existsSync(SANDBOX_OFFSETS_PATH)) {
|
|
1932
|
+
try {
|
|
1933
|
+
const loaded = JSON.parse(fs.readFileSync(SANDBOX_OFFSETS_PATH, "utf8"));
|
|
1934
|
+
if (loaded && typeof loaded === "object") {
|
|
1935
|
+
state = {
|
|
1936
|
+
offsets: loaded.offsets || {},
|
|
1937
|
+
lastPromptBySession: loaded.lastPromptBySession || {},
|
|
1938
|
+
whisperedBySession: loaded.whisperedBySession || {},
|
|
1939
|
+
notifiedSessions: loaded.notifiedSessions || {},
|
|
1940
|
+
};
|
|
1941
|
+
}
|
|
1942
|
+
} catch {
|
|
1943
|
+
// ignore corrupt offsets file
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
if (opts.isOnce) {
|
|
1948
|
+
const res = await scanSandboxTranscriptsOnce(opts, state);
|
|
1949
|
+
if (opts.jsonOutput) {
|
|
1950
|
+
process.stdout.write(JSON.stringify(res, null, 2) + "\n");
|
|
1951
|
+
} else {
|
|
1952
|
+
console.log(
|
|
1953
|
+
`[/ ml] Sandbox scan complete: ${res.processed_events} event(s) evaluated, ${res.memories_assimilated} rule(s) assimilated, ${res.interventions_triggered} intervention(s) triggered.`
|
|
1954
|
+
);
|
|
1955
|
+
}
|
|
1956
|
+
return;
|
|
1957
|
+
}
|
|
1958
|
+
|
|
1959
|
+
while (true) {
|
|
1960
|
+
await scanSandboxTranscriptsOnce(opts, state);
|
|
1961
|
+
await new Promise((r) => setTimeout(r, opts.intervalMs || 1500));
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
function drainPendingSandboxIntervention() {
|
|
1966
|
+
try {
|
|
1967
|
+
if (!fs.existsSync(SANDBOX_INTERVENTION_PATH)) return null;
|
|
1968
|
+
const saved = JSON.parse(fs.readFileSync(SANDBOX_INTERVENTION_PATH, "utf8"));
|
|
1969
|
+
fs.unlinkSync(SANDBOX_INTERVENTION_PATH);
|
|
1970
|
+
if (saved && saved.intervention_message && Date.now() - Number(saved.timestamp || 0) < 600000) {
|
|
1971
|
+
return String(saved.intervention_message);
|
|
1972
|
+
}
|
|
1973
|
+
} catch {
|
|
1974
|
+
// ignore
|
|
1975
|
+
}
|
|
1976
|
+
return null;
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1304
1979
|
if (parsed.isInstallHooks) {
|
|
1305
1980
|
installAmbientHooks(parsed.apiKey);
|
|
1306
1981
|
process.exit(0);
|
|
1307
1982
|
}
|
|
1308
1983
|
|
|
1984
|
+
if (parsed.forgetId) {
|
|
1985
|
+
apiRequest(parsed, "DELETE", `/v1/memories/${encodeURIComponent(parsed.forgetId)}`)
|
|
1986
|
+
.then((res) => {
|
|
1987
|
+
if (parsed.jsonOutput) {
|
|
1988
|
+
process.stdout.write(JSON.stringify(res || { status: "deleted" }, null, 2) + "\n");
|
|
1989
|
+
} else {
|
|
1990
|
+
console.log(`[/ ml] Deleted memory ${parsed.forgetId}.`);
|
|
1991
|
+
}
|
|
1992
|
+
process.exit(0);
|
|
1993
|
+
})
|
|
1994
|
+
.catch((err) => {
|
|
1995
|
+
console.error(`Error: ${err.message || err}`);
|
|
1996
|
+
process.exit(1);
|
|
1997
|
+
});
|
|
1998
|
+
return;
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
if (parsed.isSyncRules) {
|
|
2002
|
+
runSyncRulesCommand(parsed)
|
|
2003
|
+
.then(() => process.exit(0))
|
|
2004
|
+
.catch(() => process.exit(0));
|
|
2005
|
+
return;
|
|
2006
|
+
}
|
|
2007
|
+
|
|
2008
|
+
if (parsed.isWatchSandbox) {
|
|
2009
|
+
runWatchSandboxCommand(parsed)
|
|
2010
|
+
.then(() => process.exit(0))
|
|
2011
|
+
.catch(() => process.exit(0));
|
|
2012
|
+
return;
|
|
2013
|
+
}
|
|
2014
|
+
|
|
1309
2015
|
if (parsed.isStatus) {
|
|
1310
2016
|
runStatusCommand(parsed)
|
|
1311
2017
|
.then(() => process.exit(0))
|
|
@@ -1326,7 +2032,7 @@ if (parsed.isHook) {
|
|
|
1326
2032
|
return;
|
|
1327
2033
|
}
|
|
1328
2034
|
|
|
1329
|
-
const
|
|
2035
|
+
const MEMORY_TOOLS = [
|
|
1330
2036
|
{
|
|
1331
2037
|
name: "add_memory",
|
|
1332
2038
|
description:
|
|
@@ -1338,6 +2044,30 @@ const STANDARD_TOOLS = [
|
|
|
1338
2044
|
user_id: { type: "string" },
|
|
1339
2045
|
memory_id: { type: "string" },
|
|
1340
2046
|
metadata: { type: "object" },
|
|
2047
|
+
record_tier: { type: "string", enum: ["fact", "rule"] },
|
|
2048
|
+
slot_key: { type: "string" },
|
|
2049
|
+
scope: { type: "object" },
|
|
2050
|
+
},
|
|
2051
|
+
required: ["text"],
|
|
2052
|
+
},
|
|
2053
|
+
},
|
|
2054
|
+
{
|
|
2055
|
+
name: "add_scoped_rule",
|
|
2056
|
+
description:
|
|
2057
|
+
"Store an operational rule or constraint (Tier B) with optional negative contrastive enforcement (DO / DON'T) and execution scope.",
|
|
2058
|
+
inputSchema: {
|
|
2059
|
+
type: "object",
|
|
2060
|
+
properties: {
|
|
2061
|
+
text: { type: "string", description: "Natural language rule or constraint text" },
|
|
2062
|
+
rule_id: { type: "string", description: "Optional unique rule identifier" },
|
|
2063
|
+
do: { type: "string", description: "Positive behavior statement" },
|
|
2064
|
+
dont: { type: "string", description: "Negative prohibition statement" },
|
|
2065
|
+
scope: {
|
|
2066
|
+
type: "object",
|
|
2067
|
+
description: "Rule scope matching criteria (file_paths, tool_names, environments, git_branches)",
|
|
2068
|
+
},
|
|
2069
|
+
user_id: { type: "string" },
|
|
2070
|
+
metadata: { type: "object" },
|
|
1341
2071
|
},
|
|
1342
2072
|
required: ["text"],
|
|
1343
2073
|
},
|
|
@@ -1351,10 +2081,30 @@ const STANDARD_TOOLS = [
|
|
|
1351
2081
|
query: { type: "string" },
|
|
1352
2082
|
user_id: { type: "string" },
|
|
1353
2083
|
limit: { type: "integer", default: 5 },
|
|
2084
|
+
record_tier: { type: "string", enum: ["fact", "rule"] },
|
|
1354
2085
|
},
|
|
1355
2086
|
required: ["query"],
|
|
1356
2087
|
},
|
|
1357
2088
|
},
|
|
2089
|
+
{
|
|
2090
|
+
name: "get_cache_aligned_prompt",
|
|
2091
|
+
description:
|
|
2092
|
+
"Retrieve scoped rules and dynamic facts formatted into Zone 1 (static rules) and Zone 2 (dynamic facts) with cache breakpoint delimiter for optimal KV prefix reuse.",
|
|
2093
|
+
inputSchema: {
|
|
2094
|
+
type: "object",
|
|
2095
|
+
properties: {
|
|
2096
|
+
user_turn: { type: "string", description: "Current user prompt or task turn" },
|
|
2097
|
+
context: {
|
|
2098
|
+
type: "object",
|
|
2099
|
+
description: "Active environment context (file_path, tool_name, environment, git_branch)",
|
|
2100
|
+
},
|
|
2101
|
+
top_k: { type: "integer", default: 5 },
|
|
2102
|
+
user_id: { type: "string" },
|
|
2103
|
+
enable_cache_breakpoint: { type: "boolean", default: true },
|
|
2104
|
+
},
|
|
2105
|
+
required: ["user_turn"],
|
|
2106
|
+
},
|
|
2107
|
+
},
|
|
1358
2108
|
{
|
|
1359
2109
|
name: "get_memories",
|
|
1360
2110
|
description: "List stored memories for a user or project scope.",
|
|
@@ -1377,6 +2127,9 @@ const STANDARD_TOOLS = [
|
|
|
1377
2127
|
required: ["memory_id"],
|
|
1378
2128
|
},
|
|
1379
2129
|
},
|
|
2130
|
+
];
|
|
2131
|
+
|
|
2132
|
+
const CODE_TOOLS = [
|
|
1380
2133
|
{
|
|
1381
2134
|
name: "index_repository",
|
|
1382
2135
|
description:
|
|
@@ -1435,11 +2188,13 @@ const STANDARD_TOOLS = [
|
|
|
1435
2188
|
},
|
|
1436
2189
|
];
|
|
1437
2190
|
|
|
2191
|
+
const STANDARD_TOOLS = [...MEMORY_TOOLS, ...CODE_TOOLS];
|
|
2192
|
+
|
|
1438
2193
|
const CODE_MODE_TOOLS = [
|
|
1439
2194
|
{
|
|
1440
2195
|
name: "execute_memory_code",
|
|
1441
2196
|
description:
|
|
1442
|
-
"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.",
|
|
2197
|
+
"Compact meta-tool (91% token savings) dispatching memory & code actions (`add_memory`, `add_scoped_rule`, `search_memories`, `get_memories`, `get_cache_aligned_prompt`, `forget_memory`, `index_repository`, `search_code_by_behavior`, `find_bug_candidates`, `intervene_memory`) to `/ ml` Cloud.",
|
|
1443
2198
|
inputSchema: {
|
|
1444
2199
|
type: "object",
|
|
1445
2200
|
properties: {
|
|
@@ -1447,8 +2202,10 @@ const CODE_MODE_TOOLS = [
|
|
|
1447
2202
|
type: "string",
|
|
1448
2203
|
enum: [
|
|
1449
2204
|
"add_memory",
|
|
2205
|
+
"add_scoped_rule",
|
|
1450
2206
|
"search_memories",
|
|
1451
2207
|
"get_memories",
|
|
2208
|
+
"get_cache_aligned_prompt",
|
|
1452
2209
|
"forget_memory",
|
|
1453
2210
|
"index_repository",
|
|
1454
2211
|
"search_code_by_behavior",
|
|
@@ -1642,6 +2399,12 @@ async function dispatchTool(opts, name, args = {}) {
|
|
|
1642
2399
|
|
|
1643
2400
|
if (name === "add_memory") {
|
|
1644
2401
|
const rawText = args.text !== undefined ? args.text : args.messages;
|
|
2402
|
+
const meta = {
|
|
2403
|
+
...(args.metadata || {}),
|
|
2404
|
+
...(args.record_tier ? { record_tier: String(args.record_tier) } : {}),
|
|
2405
|
+
...(args.slot_key ? { slot_key: String(args.slot_key) } : {}),
|
|
2406
|
+
...(args.scope ? { scope: args.scope } : {}),
|
|
2407
|
+
};
|
|
1645
2408
|
const messagesPayload = Array.isArray(rawText)
|
|
1646
2409
|
? rawText
|
|
1647
2410
|
: [
|
|
@@ -1649,14 +2412,38 @@ async function dispatchTool(opts, name, args = {}) {
|
|
|
1649
2412
|
role: "user",
|
|
1650
2413
|
content: String(rawText || ""),
|
|
1651
2414
|
...(args.memory_id ? { id: String(args.memory_id) } : {}),
|
|
1652
|
-
|
|
2415
|
+
metadata: meta,
|
|
1653
2416
|
},
|
|
1654
2417
|
];
|
|
1655
2418
|
return apiRequest(opts, "POST", "/v1/memories", {
|
|
1656
2419
|
messages: messagesPayload,
|
|
1657
2420
|
user_id: uid,
|
|
1658
2421
|
memory_id: args.memory_id,
|
|
1659
|
-
metadata:
|
|
2422
|
+
metadata: meta,
|
|
2423
|
+
...(args.record_tier ? { record_tier: String(args.record_tier) } : {}),
|
|
2424
|
+
...(args.slot_key ? { slot_key: String(args.slot_key) } : {}),
|
|
2425
|
+
});
|
|
2426
|
+
}
|
|
2427
|
+
if (name === "add_scoped_rule") {
|
|
2428
|
+
const text = String(args.text || args.rule || "");
|
|
2429
|
+
const ruleId = args.rule_id || args.ruleId || `rule_${Math.floor(Math.random() * 900000 + 100000)}`;
|
|
2430
|
+
const contrastiveObj = args.contrastive && typeof args.contrastive === "object" ? args.contrastive : {};
|
|
2431
|
+
const doVal = args.do || contrastiveObj.canonical || contrastiveObj.do || text;
|
|
2432
|
+
const dontVal = args.dont || contrastiveObj.negative_pattern || contrastiveObj.dont || "";
|
|
2433
|
+
const meta = {
|
|
2434
|
+
...(args.metadata || {}),
|
|
2435
|
+
rule_id: ruleId,
|
|
2436
|
+
record_tier: "rule",
|
|
2437
|
+
scope: args.scope || {},
|
|
2438
|
+
contrastive: { do: doVal, dont: dontVal },
|
|
2439
|
+
};
|
|
2440
|
+
return apiRequest(opts, "POST", "/v1/memory/ingest", {
|
|
2441
|
+
text,
|
|
2442
|
+
user_id: uid,
|
|
2443
|
+
record_tier: "rule",
|
|
2444
|
+
slot_key: args.slot_key,
|
|
2445
|
+
documents: [{ text, id: ruleId, user_id: uid, metadata: meta }],
|
|
2446
|
+
metadata: meta,
|
|
1660
2447
|
});
|
|
1661
2448
|
}
|
|
1662
2449
|
if (name === "search_memories") {
|
|
@@ -1664,6 +2451,7 @@ async function dispatchTool(opts, name, args = {}) {
|
|
|
1664
2451
|
const mergedFilters = {
|
|
1665
2452
|
...(args.filters && typeof args.filters === "object" ? args.filters : {}),
|
|
1666
2453
|
...(args.include_code !== undefined ? { include_code: Boolean(args.include_code) } : {}),
|
|
2454
|
+
...(args.record_tier ? { record_tier: String(args.record_tier) } : {}),
|
|
1667
2455
|
...(args.kind ? { kind: String(args.kind) } : {}),
|
|
1668
2456
|
};
|
|
1669
2457
|
return apiRequest(opts, "POST", "/v1/memories/search", {
|
|
@@ -1674,6 +2462,84 @@ async function dispatchTool(opts, name, args = {}) {
|
|
|
1674
2462
|
...(Object.keys(mergedFilters).length > 0 ? { filters: mergedFilters } : {}),
|
|
1675
2463
|
});
|
|
1676
2464
|
}
|
|
2465
|
+
if (name === "get_cache_aligned_prompt") {
|
|
2466
|
+
const userTurn = String(args.user_turn || args.query || args.prompt || "");
|
|
2467
|
+
const topK = Number(args.top_k || 5);
|
|
2468
|
+
const resolvedContext = args.context && typeof args.context === "object"
|
|
2469
|
+
? args.context
|
|
2470
|
+
: {
|
|
2471
|
+
...(args.active_file ? { file_path: args.active_file } : {}),
|
|
2472
|
+
...(args.branch ? { git_branch: args.branch } : {}),
|
|
2473
|
+
...(args.env ? { environment: args.env } : {}),
|
|
2474
|
+
};
|
|
2475
|
+
const rulesRes = await apiRequest(opts, "POST", "/v1/memory/query", {
|
|
2476
|
+
prompt: userTurn,
|
|
2477
|
+
user_id: uid,
|
|
2478
|
+
top_k: 20,
|
|
2479
|
+
record_tier: "rule",
|
|
2480
|
+
context: resolvedContext,
|
|
2481
|
+
});
|
|
2482
|
+
const factsRes = await apiRequest(opts, "POST", "/v1/memory/query", {
|
|
2483
|
+
prompt: userTurn,
|
|
2484
|
+
user_id: uid,
|
|
2485
|
+
top_k: topK,
|
|
2486
|
+
record_tier: "fact",
|
|
2487
|
+
});
|
|
2488
|
+
const rawRules = rulesRes.results || rulesRes.memories || [];
|
|
2489
|
+
const rawFacts = factsRes.results || factsRes.memories || [];
|
|
2490
|
+
const activeRules = rawRules.map((r) => {
|
|
2491
|
+
const rMeta = r.metadata || {};
|
|
2492
|
+
const c = rMeta.contrastive || {};
|
|
2493
|
+
return {
|
|
2494
|
+
rule_id: String(r.id || rMeta.rule_id || "rule"),
|
|
2495
|
+
do: String(c.do || r.text || ""),
|
|
2496
|
+
dont: String(c.dont || ""),
|
|
2497
|
+
};
|
|
2498
|
+
});
|
|
2499
|
+
const zone1Lines = [];
|
|
2500
|
+
if (activeRules.length > 0) {
|
|
2501
|
+
zone1Lines.push("<rules>");
|
|
2502
|
+
for (const r of activeRules) {
|
|
2503
|
+
zone1Lines.push(` <rule id="${r.rule_id}">\n <do>${r.do}</do>\n <dont>${r.dont}</dont>\n </rule>`);
|
|
2504
|
+
}
|
|
2505
|
+
zone1Lines.push("</rules>");
|
|
2506
|
+
}
|
|
2507
|
+
const zone1Text = zone1Lines.join("\n");
|
|
2508
|
+
const zone2Lines = [];
|
|
2509
|
+
if (rawFacts.length > 0) {
|
|
2510
|
+
zone2Lines.push("<facts>");
|
|
2511
|
+
for (const f of rawFacts) {
|
|
2512
|
+
const t = typeof f === "string" ? f : f.text || f.memory || "";
|
|
2513
|
+
if (t) zone2Lines.push(` <fact>${t}</fact>`);
|
|
2514
|
+
}
|
|
2515
|
+
zone2Lines.push("</facts>");
|
|
2516
|
+
}
|
|
2517
|
+
const zone2Text = zone2Lines.join("\n");
|
|
2518
|
+
const enableBp = args.enable_cache_breakpoint !== false;
|
|
2519
|
+
const parts = [];
|
|
2520
|
+
if (zone1Text) parts.push(zone1Text);
|
|
2521
|
+
if (enableBp && zone1Text) parts.push("<!-- cache_control: ephemeral_breakpoint -->");
|
|
2522
|
+
if (zone2Text) parts.push(zone2Text);
|
|
2523
|
+
parts.push(userTurn);
|
|
2524
|
+
const fullPrompt = parts.filter(Boolean).join("\n\n");
|
|
2525
|
+
const z1Tok = zone1Text ? Math.max(1, Math.floor(zone1Text.length / 4)) : 0;
|
|
2526
|
+
const z2Tok = zone2Text ? Math.max(1, Math.floor(zone2Text.length / 4)) : 0;
|
|
2527
|
+
const uTok = Math.max(1, Math.floor(userTurn.length / 4));
|
|
2528
|
+
const totTok = z1Tok + z2Tok + uTok;
|
|
2529
|
+
return {
|
|
2530
|
+
full_prompt_text: fullPrompt,
|
|
2531
|
+
zone1_rules_text: zone1Text,
|
|
2532
|
+
zone2_facts_text: zone2Text,
|
|
2533
|
+
has_cache_breakpoint: enableBp && Boolean(zone1Text),
|
|
2534
|
+
token_economics: {
|
|
2535
|
+
zone1_tokens_estimated: z1Tok,
|
|
2536
|
+
zone2_tokens_estimated: z2Tok,
|
|
2537
|
+
user_tokens_estimated: uTok,
|
|
2538
|
+
total_tokens_estimated: totTok,
|
|
2539
|
+
prefix_cache_eligible_ratio: totTok > 0 ? Number((z1Tok / totTok).toFixed(3)) : 0.0,
|
|
2540
|
+
},
|
|
2541
|
+
};
|
|
2542
|
+
}
|
|
1677
2543
|
if (name === "get_memories") {
|
|
1678
2544
|
const paramsObj = { user_id: uid, limit: String(args.limit || 50) };
|
|
1679
2545
|
if (args.include_code !== undefined) paramsObj.include_code = String(Boolean(args.include_code));
|
|
@@ -1831,7 +2697,7 @@ rl.on("line", (line) => {
|
|
|
1831
2697
|
const tools = parsed.codeMode
|
|
1832
2698
|
? CODE_MODE_TOOLS
|
|
1833
2699
|
: parsed.codeOnly
|
|
1834
|
-
?
|
|
2700
|
+
? CODE_TOOLS
|
|
1835
2701
|
: parsed.passiveWrites
|
|
1836
2702
|
? STANDARD_TOOLS.filter((t) => t.name !== "add_memory")
|
|
1837
2703
|
: STANDARD_TOOLS;
|
|
@@ -1841,11 +2707,16 @@ rl.on("line", (line) => {
|
|
|
1841
2707
|
if (method === "tools/call") {
|
|
1842
2708
|
try {
|
|
1843
2709
|
const result = await dispatchTool(parsed, params?.name, params?.arguments);
|
|
2710
|
+
const contentBlocks = [{ type: "text", text: JSON.stringify(result) }];
|
|
2711
|
+
const pendingIntervention = drainPendingSandboxIntervention();
|
|
2712
|
+
if (pendingIntervention) {
|
|
2713
|
+
contentBlocks.push({ type: "text", text: pendingIntervention });
|
|
2714
|
+
}
|
|
1844
2715
|
process.stdout.write(
|
|
1845
2716
|
JSON.stringify({
|
|
1846
2717
|
jsonrpc: "2.0",
|
|
1847
2718
|
id,
|
|
1848
|
-
result: { content:
|
|
2719
|
+
result: { content: contentBlocks },
|
|
1849
2720
|
}) + "\n"
|
|
1850
2721
|
);
|
|
1851
2722
|
} catch (err) {
|