@slashml/memory 1.0.16 → 1.1.1

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,8 +10,19 @@ 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.16";
13
+ const PACKAGE_VERSION = "1.1.1";
14
14
  const MAX_STOP_BLOCKS_PER_PROMPT = 3;
15
+ let lastObservedVaultRevision = 0;
16
+
17
+ function updateObservedVaultRevisionFromResponse(res) {
18
+ if (!res || !res.headers || typeof res.headers.get !== "function") return;
19
+ const raw = res.headers.get("x-slashml-vault-revision");
20
+ if (!raw) return;
21
+ const parsedRev = Number(raw);
22
+ if (Number.isFinite(parsedRev) && parsedRev > lastObservedVaultRevision) {
23
+ lastObservedVaultRevision = parsedRev;
24
+ }
25
+ }
15
26
 
16
27
  function printHelp() {
17
28
  console.log(`@slashml/memory v${PACKAGE_VERSION} -- Official CLI & MCP Stdio Server for / ml (SlashML · https://slashml.ai)
@@ -37,6 +48,7 @@ Options:
37
48
  --code-only Expose only code & bug-localization MCP tools
38
49
  --code-mode Expose compact single meta-tool (execute_memory_code)
39
50
  --init Write ml-memory MCP entry to Cursor, Windsurf, or .mcp.json
51
+ --ellipsis With --init / init, scaffold .ellipsis/environments/slashml.yaml & PR review agent YAML
40
52
  --skill <name> Filter IDE config target during --init (default: ml-memory)
41
53
  --write-env Save SLASHML_API_KEY to .env in the current directory
42
54
  --hook Run as an ambient IDE/agent lifecycle hook (reads hook JSON from stdin)
@@ -54,7 +66,15 @@ Options:
54
66
  --file <path> Import memories from a local JSON, JSONL, CSV, or Markdown export file
55
67
  import-local, --import-local Import local coding-agent memories (~/.claude/projects/*/memory/*.md, CLAUDE.md, .cursorrules, .windsurfrules, .cursor/rules)
56
68
  --dry-run Preview discovered memories during migrate or import-local without writing to / ml
57
- --json Format status/sync/migrate output as JSON
69
+ mint-token, --mint-token Mint a scoped delegated worker/coordinator token (sml_st_*)
70
+ revoke-token, --revoke-token Instantly revoke delegated tokens for --agent <id> or --all
71
+ promote, --promote Promote validated swarm run findings (--run <id>) to durable project memory
72
+ wrap-mcp, --wrap-mcp Wrap any stdio or HTTP MCP server with synchronous / ml PreToolUse & redaction guardrails
73
+ install-shell-guards Install POSIX PATH shims enforcing / ml PreToolUse guardrails on mutating shell CLIs
74
+ guard-exec Execute a shell command behind synchronous / ml PreToolUse policy evaluation
75
+ --run, --run-id <id> Active swarm run identifier (or SLASHML_RUN_ID)
76
+ --project, --project-id <id> Project scope identifier (or SLASHML_PROJECT_ID)
77
+ --json Format status/sync/migrate/token/promote output as JSON
58
78
  --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)
59
79
  --verify <work-email> <code> Verify 6-digit code and print the new SLASHML_API_KEY to stdout`);
60
80
  }
@@ -186,6 +206,9 @@ function parseCliArgs(argv) {
186
206
  let baseUrl = (process.env.SLASHML_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
187
207
  let consoleUrl = (process.env.SLASHML_CONSOLE_URL || DEFAULT_CONSOLE_URL).replace(/\/+$/, "");
188
208
  let userId = process.env.SLASHML_USER_ID || "default";
209
+ let explicitUserId = (process.env.SLASHML_USER_ID || "").trim() || null;
210
+ let projectId = (process.env.SLASHML_PROJECT_ID || "").trim() || null;
211
+ let runId = (process.env.SLASHML_RUN_ID || "").trim() || null;
189
212
  let agentId = (process.env.SLASHML_AGENT_ID || "").trim() || null;
190
213
  let redactPolicy = (process.env.SLASHML_REDACT_POLICY || "").trim() || null;
191
214
  let redactScope = (process.env.SLASHML_REDACT_SCOPE || "").trim() || null;
@@ -204,6 +227,7 @@ function parseCliArgs(argv) {
204
227
  let isStatus = false;
205
228
  let jsonOutput = false;
206
229
  let isSyncRules = false;
230
+ let isEllipsis = false;
207
231
  let isWatchSandbox = false;
208
232
  let isDaemon = false;
209
233
  let isOnce = false;
@@ -217,15 +241,160 @@ function parseCliArgs(argv) {
217
241
  let importFile = null;
218
242
  let isImportLocal = false;
219
243
  let isDryRun = false;
244
+ let isMintToken = false;
245
+ let tokenTier = "worker";
246
+ let accessMode = null;
247
+ let ttlSeconds = 3600;
248
+ let canDelegate = false;
249
+ let printEnv = false;
250
+ let isRevokeToken = false;
251
+ let revokeAll = false;
252
+ let isPromote = false;
253
+ let promoteMemoryIds = [];
254
+ let discardUnpromoted = false;
255
+ let isWrapMcp = false;
256
+ let wrapServerName = null;
257
+ let upstreamUrl = null;
258
+ let upstreamCmd = null;
259
+ let wrapArgv = [];
260
+ let isGuardExec = false;
261
+ let guardExecArgv = [];
262
+ let isInstallShellGuards = false;
263
+ let guardBinDir = process.env.SLASHML_GUARD_BIN_DIR || "/tmp/.slashml-guards/bin";
264
+ let guardCommands = null;
265
+ let profilePath = null;
266
+ let guardTimeoutMs = null;
267
+ let failMode = (process.env.SLASHML_GUARD_FAIL_MODE || "open").trim().toLowerCase();
220
268
 
221
269
  for (let i = 0; i < argv.length; i++) {
222
270
  const arg = argv[i];
223
- if (arg === "-h" || arg === "--help" || arg === "help") {
271
+ if (arg === "wrap-mcp" || arg === "--wrap-mcp") {
272
+ isWrapMcp = true;
273
+ for (let j = i + 1; j < argv.length; j++) {
274
+ const w = argv[j];
275
+ if (w === "--") {
276
+ wrapArgv = argv.slice(j + 1);
277
+ break;
278
+ } else if ((w === "--name" || w === "--server-name") && j + 1 < argv.length) {
279
+ wrapServerName = argv[++j].trim() || null;
280
+ } else if ((w === "--upstream-url" || w === "--url") && j + 1 < argv.length) {
281
+ upstreamUrl = argv[++j].trim().replace(/\/+$/, "");
282
+ } else if (w === "--upstream-cmd" && j + 1 < argv.length) {
283
+ upstreamCmd = argv[++j];
284
+ } else if (w === "--api-key" && j + 1 < argv.length) {
285
+ apiKey = argv[++j];
286
+ } else if (w === "--base-url" && j + 1 < argv.length) {
287
+ baseUrl = argv[++j].replace(/\/+$/, "");
288
+ } else if ((w === "--run" || w === "--run-id") && j + 1 < argv.length) {
289
+ runId = argv[++j].trim() || null;
290
+ } else if ((w === "--project" || w === "--project-id") && j + 1 < argv.length) {
291
+ projectId = argv[++j].trim() || null;
292
+ } else if ((w === "--user" || w === "--user-id") && j + 1 < argv.length) {
293
+ userId = argv[++j];
294
+ explicitUserId = userId;
295
+ } else if ((w === "--agent" || w === "--agent-id") && j + 1 < argv.length) {
296
+ agentId = argv[++j].trim() || null;
297
+ } else if (w === "--redact-policy" && j + 1 < argv.length) {
298
+ redactPolicy = argv[++j].trim() || null;
299
+ } else if (w === "--redact-scope" && j + 1 < argv.length) {
300
+ redactScope = argv[++j].trim() || null;
301
+ } else if (w === "--timeout-ms" && j + 1 < argv.length) {
302
+ guardTimeoutMs = Math.max(100, Number(argv[++j]) || 5000);
303
+ } else if (w === "--fail-mode" && j + 1 < argv.length) {
304
+ failMode = argv[++j].trim().toLowerCase();
305
+ } else if (!w.startsWith("-")) {
306
+ wrapArgv = argv.slice(j);
307
+ break;
308
+ }
309
+ }
310
+ break;
311
+ } else if (arg === "guard-exec" || arg === "--guard-exec") {
312
+ isGuardExec = true;
313
+ for (let j = i + 1; j < argv.length; j++) {
314
+ const g = argv[j];
315
+ if (g === "--") {
316
+ guardExecArgv = argv.slice(j + 1);
317
+ break;
318
+ } else if (g === "--api-key" && j + 1 < argv.length) {
319
+ apiKey = argv[++j];
320
+ } else if (g === "--base-url" && j + 1 < argv.length) {
321
+ baseUrl = argv[++j].replace(/\/+$/, "");
322
+ } else if ((g === "--run" || g === "--run-id") && j + 1 < argv.length) {
323
+ runId = argv[++j].trim() || null;
324
+ } else if ((g === "--project" || g === "--project-id") && j + 1 < argv.length) {
325
+ projectId = argv[++j].trim() || null;
326
+ } else if ((g === "--user" || g === "--user-id") && j + 1 < argv.length) {
327
+ userId = argv[++j];
328
+ explicitUserId = userId;
329
+ } else if ((g === "--agent" || g === "--agent-id") && j + 1 < argv.length) {
330
+ agentId = argv[++j].trim() || null;
331
+ } else if (g === "--redact-policy" && j + 1 < argv.length) {
332
+ redactPolicy = argv[++j].trim() || null;
333
+ } else if (g === "--timeout-ms" && j + 1 < argv.length) {
334
+ guardTimeoutMs = Math.max(100, Number(argv[++j]) || 1500);
335
+ } else if (g === "--fail-mode" && j + 1 < argv.length) {
336
+ failMode = argv[++j].trim().toLowerCase();
337
+ } else if (g === "--bin-dir" && j + 1 < argv.length) {
338
+ guardBinDir = argv[++j];
339
+ } else {
340
+ guardExecArgv = argv.slice(j);
341
+ break;
342
+ }
343
+ }
344
+ break;
345
+ } else if (arg === "-h" || arg === "--help" || arg === "help") {
224
346
  isHelp = true;
225
347
  } else if (arg === "-v" || arg === "--version" || arg === "version") {
226
348
  isVersion = true;
227
349
  } else if (arg === "init" || arg === "--init") {
228
350
  isInit = true;
351
+ } else if (arg === "--ellipsis") {
352
+ isEllipsis = true;
353
+ } else if (arg === "mint-token" || arg === "--mint-token") {
354
+ isMintToken = true;
355
+ } else if (arg === "revoke-token" || arg === "--revoke-token") {
356
+ isRevokeToken = true;
357
+ } else if (arg === "promote" || arg === "--promote") {
358
+ isPromote = true;
359
+ } else if (arg === "install-shell-guards" || arg === "--install-shell-guards") {
360
+ isInstallShellGuards = true;
361
+ } else if (arg === "--tier" && i + 1 < argv.length) {
362
+ tokenTier = argv[++i].trim().toLowerCase();
363
+ } else if (arg === "--access-mode" && i + 1 < argv.length) {
364
+ accessMode = argv[++i].trim().toLowerCase();
365
+ } else if ((arg === "--ttl" || arg === "--ttl-seconds") && i + 1 < argv.length) {
366
+ ttlSeconds = Math.max(1, Number(argv[++i]) || 3600);
367
+ } else if (arg === "--can-delegate") {
368
+ canDelegate = true;
369
+ } else if (arg === "--env" || arg === "--print-env") {
370
+ printEnv = true;
371
+ } else if (arg === "--all") {
372
+ revokeAll = true;
373
+ } else if (arg === "--memory-ids" && i + 1 < argv.length) {
374
+ const ids = argv[++i]
375
+ .split(",")
376
+ .map((s) => s.trim())
377
+ .filter(Boolean);
378
+ promoteMemoryIds.push(...ids);
379
+ } else if (arg === "--discard-unpromoted") {
380
+ discardUnpromoted = true;
381
+ } else if ((arg === "--run" || arg === "--run-id") && i + 1 < argv.length) {
382
+ runId = argv[++i].trim() || null;
383
+ } else if ((arg === "--project" || arg === "--project-id") && i + 1 < argv.length) {
384
+ projectId = argv[++i].trim() || null;
385
+ } else if (arg === "--bin-dir" && i + 1 < argv.length) {
386
+ guardBinDir = argv[++i];
387
+ } else if (arg === "--commands" && i + 1 < argv.length) {
388
+ guardCommands = argv[++i]
389
+ .split(",")
390
+ .map((s) => s.trim())
391
+ .filter(Boolean);
392
+ } else if (arg === "--profile" && i + 1 < argv.length) {
393
+ profilePath = argv[++i];
394
+ } else if (arg === "--timeout-ms" && i + 1 < argv.length) {
395
+ guardTimeoutMs = Math.max(100, Number(argv[++i]) || 1500);
396
+ } else if (arg === "--fail-mode" && i + 1 < argv.length) {
397
+ failMode = argv[++i].trim().toLowerCase();
229
398
  } else if (arg === "--hook" || arg === "hook") {
230
399
  isHook = true;
231
400
  } else if (arg === "--hook-daemon") {
@@ -276,9 +445,10 @@ function parseCliArgs(argv) {
276
445
  baseUrl = argv[++i].replace(/\/+$/, "");
277
446
  } else if (arg === "--console-url" && i + 1 < argv.length) {
278
447
  consoleUrl = argv[++i].replace(/\/+$/, "");
279
- } else if (arg === "--user-id" && i + 1 < argv.length) {
448
+ } else if ((arg === "--user" || arg === "--user-id") && i + 1 < argv.length) {
280
449
  userId = argv[++i];
281
- } else if (arg === "--agent-id" && i + 1 < argv.length) {
450
+ explicitUserId = userId;
451
+ } else if ((arg === "--agent" || arg === "--agent-id") && i + 1 < argv.length) {
282
452
  agentId = argv[++i].trim() || null;
283
453
  } else if (arg === "--redact-policy" && i + 1 < argv.length) {
284
454
  redactPolicy = argv[++i].trim() || null;
@@ -317,6 +487,9 @@ function parseCliArgs(argv) {
317
487
  baseUrl,
318
488
  consoleUrl,
319
489
  userId,
490
+ explicitUserId,
491
+ projectId,
492
+ runId,
320
493
  agentId,
321
494
  redactPolicy,
322
495
  redactScope,
@@ -335,6 +508,7 @@ function parseCliArgs(argv) {
335
508
  isStatus,
336
509
  jsonOutput,
337
510
  isSyncRules,
511
+ isEllipsis,
338
512
  isWatchSandbox,
339
513
  isDaemon,
340
514
  isOnce,
@@ -348,6 +522,30 @@ function parseCliArgs(argv) {
348
522
  importFile,
349
523
  isImportLocal,
350
524
  isDryRun,
525
+ isMintToken,
526
+ tokenTier,
527
+ accessMode,
528
+ ttlSeconds,
529
+ canDelegate,
530
+ printEnv,
531
+ isRevokeToken,
532
+ revokeAll,
533
+ isPromote,
534
+ promoteMemoryIds,
535
+ discardUnpromoted,
536
+ isWrapMcp,
537
+ wrapServerName,
538
+ upstreamUrl,
539
+ upstreamCmd,
540
+ wrapArgv,
541
+ isGuardExec,
542
+ guardExecArgv,
543
+ isInstallShellGuards,
544
+ guardBinDir,
545
+ guardCommands,
546
+ profilePath,
547
+ guardTimeoutMs,
548
+ failMode,
351
549
  };
352
550
  }
353
551
 
@@ -368,7 +566,12 @@ function saveApiKeyToEnvFile(apiKey, cwd = process.cwd()) {
368
566
  } else {
369
567
  content = content ? `${content.replace(/\n*$/, "")}\n${line}\n` : `${line}\n`;
370
568
  }
371
- fs.writeFileSync(envPath, content, "utf8");
569
+ fs.writeFileSync(envPath, content, { encoding: "utf8", mode: 0o600 });
570
+ try {
571
+ fs.chmodSync(envPath, 0o600);
572
+ } catch {
573
+ // ignore on platforms without POSIX chmod
574
+ }
372
575
 
373
576
  const gitignorePath = path.join(cwd, ".gitignore");
374
577
  if (fs.existsSync(gitignorePath)) {
@@ -452,7 +655,12 @@ function nativeNodeInit(skill, apiKey, repo = null, writeEnv = false, extraEnv =
452
655
  }
453
656
  delete data.mcpServers["/ml-memory"];
454
657
  data.mcpServers["ml-memory"] = serverEntry;
455
- fs.writeFileSync(target, JSON.stringify(data, null, 2) + "\n", "utf8");
658
+ fs.writeFileSync(target, JSON.stringify(data, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
659
+ try {
660
+ fs.chmodSync(target, 0o600);
661
+ } catch {
662
+ // ignore on platforms without POSIX chmod
663
+ }
456
664
  console.log(`Configured ml-memory MCP in ${target}`);
457
665
  }
458
666
  }
@@ -577,7 +785,117 @@ if (parsed.verifyEmail) {
577
785
  return;
578
786
  }
579
787
 
788
+ function initEllipsisWorkspace(opts) {
789
+ const workspaceDir = path.resolve(opts.repo || process.cwd());
790
+ const repoName = path.basename(workspaceDir.replace(/[\\/]+$/, "")) || "repo";
791
+ const userId = opts.userId || process.env.SLASHML_USER_ID || `${repoName}-org`;
792
+ const projectId = opts.projectId || process.env.SLASHML_PROJECT_ID || repoName;
793
+ const hasPkgJson = fs.existsSync(path.join(workspaceDir, "package.json"));
794
+
795
+ const envDir = path.join(workspaceDir, ".ellipsis", "environments");
796
+ const agentsDir = path.join(workspaceDir, ".ellipsis", "agents");
797
+ fs.mkdirSync(envDir, { recursive: true });
798
+ fs.mkdirSync(agentsDir, { recursive: true });
799
+
800
+ const envYamlPath = path.join(envDir, "slashml.yaml");
801
+ const agentYamlPath = path.join(agentsDir, "slashml-pr-review.yaml");
802
+
803
+ const buildBaseInputs = hasPkgJson ? ` inputs:\n - ${repoName}/package.json\n` : ` inputs: []\n`;
804
+ const npmInstallLine = hasPkgJson ? `\n cd /sandbox/${repoName}\n npm install` : "";
805
+ const envYaml = `ellipsis:
806
+ kind: environment
807
+ name: slashml
808
+
809
+ repositories:
810
+ - name: ${repoName}
811
+
812
+ variables:
813
+ - name: SLASHML_API_KEY
814
+ - name: SLASHML_USER_ID
815
+ value: ${userId}
816
+ - name: SLASHML_PROJECT_ID
817
+ value: ${projectId}
818
+
819
+ hooks:
820
+ build_base:
821
+ ${buildBaseInputs} run: |
822
+ npm install -g @slashml/mcp || sudo npm install -g @slashml/mcp${npmInstallLine}
823
+ before_start: |
824
+ cd /sandbox/${repoName}
825
+ slashml-mcp sync-rules
826
+ slashml-mcp watch-sandbox --daemon
827
+ validate: |
828
+ command -v slashml-mcp
829
+
830
+ compute:
831
+ cpu: 2
832
+ memory: 8GB
833
+ timeout: 30m
834
+
835
+ mcp_servers:
836
+ - name: ml-memory
837
+ command: slashml-mcp
838
+ env:
839
+ SLASHML_API_KEY: \${SLASHML_API_KEY}
840
+ SLASHML_USER_ID: ${userId}
841
+ SLASHML_PROJECT_ID: ${projectId}
842
+ `;
843
+
844
+ const agentYaml = `ellipsis:
845
+ kind: agent
846
+ name: slashml-pr-review
847
+ description: Stateful PR review agent powered by / ml persistent memory
848
+
849
+ trigger:
850
+ type: react
851
+ pull_request:
852
+ on: [pushed]
853
+ repositories: [${repoName}]
854
+ draft: false
855
+
856
+ session:
857
+ claude_code:
858
+ model: claude-opus-5-5
859
+ effort: high
860
+ prompt: |
861
+ Review the pull request diff against the architectural rules synced in CLAUDE.md
862
+ and query \`ml-memory\` (\`search_memories\` and \`find_bug_candidates\`) for any domain
863
+ invariants touching the modified files. If a rule is violated, explain the violation
864
+ citing the \`/ ml\` memory ID and push a fix or comment on the PR.
865
+ environment: slashml
866
+ budget:
867
+ session: 5
868
+ day: 25
869
+ `;
870
+
871
+ fs.writeFileSync(envYamlPath, envYaml, "utf8");
872
+ fs.writeFileSync(agentYamlPath, agentYaml, "utf8");
873
+ if (opts.jsonOutput) {
874
+ process.stdout.write(
875
+ JSON.stringify(
876
+ {
877
+ status: "initialized",
878
+ target: "ellipsis",
879
+ repo: repoName,
880
+ files: [envYamlPath, agentYamlPath],
881
+ },
882
+ null,
883
+ 2
884
+ ) + "\n"
885
+ );
886
+ } else {
887
+ console.log(`[/ ml] Scaffolded Ellipsis configs for "${repoName}":`);
888
+ console.log(` - ${envYamlPath}`);
889
+ console.log(` - ${agentYamlPath}`);
890
+ console.log("Next: add SLASHML_API_KEY in Ellipsis -> Secrets, then commit & push .ellipsis/.");
891
+ }
892
+ }
893
+
580
894
  if (parsed.isInit) {
895
+ if (parsed.isEllipsis) {
896
+ initEllipsisWorkspace(parsed);
897
+ process.exit(0);
898
+ }
581
899
  nativeNodeInit(parsed.skill, parsed.apiKey, parsed.repo, parsed.writeEnv, {
582
900
  agentId: parsed.agentId,
583
901
  redactPolicy: parsed.redactPolicy,
@@ -2126,6 +2444,7 @@ async function runAmbientHookMode(opts) {
2126
2444
  model: process.env.SLASHML_MODEL || undefined,
2127
2445
  user_id: opts.userId,
2128
2446
  ...(projectId ? { project_id: projectId } : {}),
2447
+ ...(opts.runId ? { run_id: opts.runId } : {}),
2129
2448
  session_id: whisperKey,
2130
2449
  ...(opts.redactPolicy ? { redact_policy: opts.redactPolicy } : {}),
2131
2450
  ...(opts.redactScope ? { redact_scope: opts.redactScope } : {}),
@@ -2390,12 +2709,28 @@ async function runAmbientHookMode(opts) {
2390
2709
  }
2391
2710
  }
2392
2711
 
2712
+ const DEFAULT_SANDBOX_RUN_DIR = path.join(os.homedir(), ".slashml", "run");
2393
2713
  const SANDBOX_INTERVENTION_PATH =
2394
- process.env.SLASHML_SANDBOX_INTERVENTION_PATH || "/tmp/slashml-sandbox-intervention.json";
2714
+ process.env.SLASHML_SANDBOX_INTERVENTION_PATH ||
2715
+ path.join(DEFAULT_SANDBOX_RUN_DIR, "slashml-sandbox-intervention.json");
2395
2716
  const SANDBOX_OFFSETS_PATH =
2396
- process.env.SLASHML_SANDBOX_OFFSETS_PATH || "/tmp/slashml-sandbox-offsets.json";
2717
+ process.env.SLASHML_SANDBOX_OFFSETS_PATH ||
2718
+ path.join(DEFAULT_SANDBOX_RUN_DIR, "slashml-sandbox-offsets.json");
2397
2719
  const SANDBOX_PID_PATH =
2398
- process.env.SLASHML_SANDBOX_PID_PATH || "/tmp/slashml-watch-sandbox.pid";
2720
+ process.env.SLASHML_SANDBOX_PID_PATH ||
2721
+ path.join(DEFAULT_SANDBOX_RUN_DIR, "slashml-watch-sandbox.pid");
2722
+
2723
+ function writePrivateRunFile(targetPath, bodyStr) {
2724
+ const dir = path.dirname(targetPath);
2725
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
2726
+ try {
2727
+ fs.chmodSync(dir, 0o700);
2728
+ } catch {}
2729
+ fs.writeFileSync(targetPath, bodyStr, { encoding: "utf8", mode: 0o600 });
2730
+ try {
2731
+ fs.chmodSync(targetPath, 0o600);
2732
+ } catch {}
2733
+ }
2399
2734
 
2400
2735
  function resolveSandboxTargets(explicitRepo) {
2401
2736
  if (explicitRepo && String(explicitRepo).trim()) {
@@ -2461,7 +2796,10 @@ async function runSyncRulesCommand(opts) {
2461
2796
  const targets = resolveSandboxTargets(opts.repo);
2462
2797
  const primaryDir = targets[0] || process.cwd();
2463
2798
  const projectId =
2464
- process.env.SLASHML_PROJECT_ID || path.basename(primaryDir.replace(/[\\/]+$/, "")) || "default";
2799
+ opts.projectId ||
2800
+ process.env.SLASHML_PROJECT_ID ||
2801
+ path.basename(primaryDir.replace(/[\\/]+$/, "")) ||
2802
+ "default";
2465
2803
 
2466
2804
  if (!opts.apiKey) {
2467
2805
  if (!opts.silent) {
@@ -2488,7 +2826,10 @@ async function runSyncRulesCommand(opts) {
2488
2826
  user_id: targetUserId,
2489
2827
  limit: "200",
2490
2828
  include_code: "false",
2829
+ inherit_scopes: "true",
2491
2830
  });
2831
+ if (projectId) q.set("project_id", projectId);
2832
+ if (opts.runId) q.set("run_id", opts.runId);
2492
2833
  const listResp = await apiRequest(opts, "GET", `/v1/memories?${q.toString()}`);
2493
2834
  const rawItems = Array.isArray(listResp)
2494
2835
  ? listResp
@@ -2573,6 +2914,8 @@ async function runSyncRulesCommand(opts) {
2573
2914
  status: "synced",
2574
2915
  project_id: projectId,
2575
2916
  user_id: opts.userId || "default",
2917
+ ...(opts.runId ? { run_id: opts.runId } : {}),
2918
+ vault_revision: lastObservedVaultRevision,
2576
2919
  synced_count: memories.length,
2577
2920
  memories,
2578
2921
  active_intervention: Boolean(activeIntervention),
@@ -2591,18 +2934,26 @@ async function runSyncRulesCommand(opts) {
2591
2934
  }
2592
2935
 
2593
2936
  function collectSandboxTranscriptFiles(extraDir) {
2594
- const roots = [];
2937
+ const rawRoots = [];
2595
2938
  const onlyExplicitDir = Boolean(extraDir && String(extraDir).trim());
2596
2939
  if (onlyExplicitDir) {
2597
- roots.push(path.resolve(String(extraDir).trim()));
2940
+ rawRoots.push(path.resolve(String(extraDir).trim()));
2598
2941
  } else {
2599
2942
  const home = os.homedir();
2600
- roots.push(
2943
+ if (process.env.CLAUDE_CONFIG_DIR && String(process.env.CLAUDE_CONFIG_DIR).trim()) {
2944
+ rawRoots.push(path.join(String(process.env.CLAUDE_CONFIG_DIR).trim(), "projects"));
2945
+ }
2946
+ if (process.env.CODEX_HOME && String(process.env.CODEX_HOME).trim()) {
2947
+ rawRoots.push(path.join(String(process.env.CODEX_HOME).trim(), "sessions"));
2948
+ }
2949
+ rawRoots.push(
2950
+ "/ellipsis/cc-config/projects",
2601
2951
  path.join(home, ".claude", "projects"),
2602
2952
  path.join(home, ".codex", "sessions"),
2603
2953
  "/tmp/slashml-transcripts"
2604
2954
  );
2605
2955
  }
2956
+ const roots = Array.from(new Set(rawRoots.filter(Boolean).map((r) => path.resolve(r))));
2606
2957
  const nowMs = Date.now();
2607
2958
  const maxAgeMs = 30 * 60 * 1000;
2608
2959
  const found = [];
@@ -2637,7 +2988,42 @@ function collectSandboxTranscriptFiles(extraDir) {
2637
2988
  return found;
2638
2989
  }
2639
2990
 
2640
- function extractEventsFromTranscriptEntry(entry) {
2991
+ function extractToolResultText(content) {
2992
+ if (typeof content === "string") return content;
2993
+ if (Array.isArray(content)) {
2994
+ return content
2995
+ .map((item) => {
2996
+ if (typeof item === "string") return item;
2997
+ if (item && typeof item === "object" && typeof item.text === "string") return item.text;
2998
+ return "";
2999
+ })
3000
+ .filter(Boolean)
3001
+ .join("\n");
3002
+ }
3003
+ if (content && typeof content === "object") {
3004
+ if (typeof content.output === "string") return content.output;
3005
+ if (typeof content.stdout === "string" || typeof content.stderr === "string") {
3006
+ return [content.stderr, content.stdout].filter(Boolean).join("\n");
3007
+ }
3008
+ }
3009
+ return "";
3010
+ }
3011
+
3012
+ function recordSessionToolUse(toolUsesMap, toolUseId, name, input) {
3013
+ if (!toolUsesMap || !toolUseId || !name) return;
3014
+ toolUsesMap[String(toolUseId)] = {
3015
+ name: String(name),
3016
+ input: input && typeof input === "object" ? input : {},
3017
+ };
3018
+ const keys = Object.keys(toolUsesMap);
3019
+ if (keys.length > 64) {
3020
+ for (const oldKey of keys.slice(0, keys.length - 64)) {
3021
+ delete toolUsesMap[oldKey];
3022
+ }
3023
+ }
3024
+ }
3025
+
3026
+ function extractEventsFromTranscriptEntry(entry, toolUsesMap = null) {
2641
3027
  const events = [];
2642
3028
  if (!entry || typeof entry !== "object") return events;
2643
3029
 
@@ -2648,6 +3034,7 @@ function extractEventsFromTranscriptEntry(entry) {
2648
3034
  prompt: String(entry.prompt || entry.text || ""),
2649
3035
  tool_name: entry.tool_name || entry.toolName || null,
2650
3036
  tool_input: entry.tool_input || entry.toolInput || null,
3037
+ tool_response: entry.tool_response || entry.toolResponse || null,
2651
3038
  });
2652
3039
  return events;
2653
3040
  }
@@ -2666,6 +3053,44 @@ function extractEventsFromTranscriptEntry(entry) {
2666
3053
  .filter((b) => b && (b.type === "text" || typeof b.text === "string"))
2667
3054
  .map((b) => String(b.text || ""))
2668
3055
  .join("\n");
3056
+ for (const b of msg.content) {
3057
+ if (!b || typeof b !== "object" || b.type !== "tool_result") continue;
3058
+ const toolUseId = b.tool_use_id || b.toolUseId || "";
3059
+ const prior = toolUsesMap && toolUseId ? toolUsesMap[String(toolUseId)] : null;
3060
+ if (!prior || !prior.name) continue;
3061
+ const resMeta =
3062
+ entry.toolUseResult && typeof entry.toolUseResult === "object"
3063
+ ? entry.toolUseResult
3064
+ : null;
3065
+ const rawOut =
3066
+ extractToolResultText(b.content) ||
3067
+ extractToolResultText(resMeta);
3068
+ const explicitCode =
3069
+ resMeta && typeof resMeta.exitCode === "number"
3070
+ ? resMeta.exitCode
3071
+ : resMeta && typeof resMeta.exit_code === "number"
3072
+ ? resMeta.exit_code
3073
+ : null;
3074
+ const isErr = Boolean(
3075
+ b.is_error ||
3076
+ b.isError ||
3077
+ (resMeta && (resMeta.interrupted || resMeta.is_error)) ||
3078
+ (explicitCode !== null && explicitCode !== 0)
3079
+ );
3080
+ const exitCode = explicitCode !== null ? explicitCode : isErr ? 1 : 0;
3081
+ const outputSlice = String(rawOut || "").trim().slice(0, 1024);
3082
+ events.push({
3083
+ hook_event_name: "PostToolUse",
3084
+ text: outputSlice,
3085
+ tool_name: String(prior.name),
3086
+ tool_input: prior.input || {},
3087
+ tool_response: {
3088
+ is_error: isErr,
3089
+ exit_code: exitCode,
3090
+ output: outputSlice,
3091
+ },
3092
+ });
3093
+ }
2669
3094
  }
2670
3095
  if (text && text.trim()) {
2671
3096
  events.push({
@@ -2674,6 +3099,7 @@ function extractEventsFromTranscriptEntry(entry) {
2674
3099
  prompt: text.trim(),
2675
3100
  tool_name: null,
2676
3101
  tool_input: null,
3102
+ tool_response: null,
2677
3103
  });
2678
3104
  }
2679
3105
  return events;
@@ -2692,6 +3118,9 @@ function extractEventsFromTranscriptEntry(entry) {
2692
3118
  textParts.push(b.text.trim());
2693
3119
  } else if (b.type === "tool_use" && b.name) {
2694
3120
  const toolIn = b.input && typeof b.input === "object" ? b.input : {};
3121
+ if (b.id) {
3122
+ recordSessionToolUse(toolUsesMap, b.id, b.name, toolIn);
3123
+ }
2695
3124
  const toolSummary =
2696
3125
  toolIn.command ||
2697
3126
  toolIn.CommandLine ||
@@ -2705,6 +3134,7 @@ function extractEventsFromTranscriptEntry(entry) {
2705
3134
  text: String(toolSummary || ""),
2706
3135
  tool_name: String(b.name),
2707
3136
  tool_input: toolIn,
3137
+ tool_response: null,
2708
3138
  });
2709
3139
  }
2710
3140
  }
@@ -2725,6 +3155,9 @@ function extractEventsFromTranscriptEntry(entry) {
2725
3155
  }
2726
3156
  })()
2727
3157
  : toolIn;
3158
+ if (tc.id) {
3159
+ recordSessionToolUse(toolUsesMap, tc.id, name, parsedIn);
3160
+ }
2728
3161
  const toolSummary =
2729
3162
  parsedIn.command ||
2730
3163
  parsedIn.CommandLine ||
@@ -2738,6 +3171,7 @@ function extractEventsFromTranscriptEntry(entry) {
2738
3171
  text: String(toolSummary || ""),
2739
3172
  tool_name: String(name),
2740
3173
  tool_input: parsedIn,
3174
+ tool_response: null,
2741
3175
  });
2742
3176
  }
2743
3177
  }
@@ -2748,6 +3182,7 @@ function extractEventsFromTranscriptEntry(entry) {
2748
3182
  text: textParts.join("\n"),
2749
3183
  tool_name: null,
2750
3184
  tool_input: null,
3185
+ tool_response: null,
2751
3186
  });
2752
3187
  }
2753
3188
  }
@@ -2756,15 +3191,20 @@ function extractEventsFromTranscriptEntry(entry) {
2756
3191
 
2757
3192
  async function scanSandboxTranscriptsOnce(opts, state) {
2758
3193
  state.whisperedBySession = state.whisperedBySession || {};
3194
+ state.toolUsesBySession = state.toolUsesBySession || {};
2759
3195
  const files = collectSandboxTranscriptFiles(opts.transcriptDir);
2760
3196
  const targets = resolveSandboxTargets(opts.repo);
2761
3197
  const primaryDir = targets[0] || process.cwd();
2762
3198
  const projectId =
2763
- process.env.SLASHML_PROJECT_ID || path.basename(primaryDir.replace(/[\\/]+$/, "")) || "default";
3199
+ opts.projectId ||
3200
+ process.env.SLASHML_PROJECT_ID ||
3201
+ path.basename(primaryDir.replace(/[\\/]+$/, "")) ||
3202
+ "default";
2764
3203
 
2765
3204
  let processedEvents = 0;
2766
3205
  let assimilatedCount = 0;
2767
3206
  let intervenedCount = 0;
3207
+ let rulesResynced = false;
2768
3208
  const interventions = [];
2769
3209
 
2770
3210
  for (const filePath of files) {
@@ -2792,6 +3232,7 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2792
3232
  state.offsets[filePath] = startOffset + Buffer.byteLength(completeStr, "utf8");
2793
3233
 
2794
3234
  const sessionId = path.basename(filePath, ".jsonl");
3235
+ state.toolUsesBySession[sessionId] = state.toolUsesBySession[sessionId] || {};
2795
3236
  const lines = completeStr.split(/\r?\n/);
2796
3237
  for (const rawLine of lines) {
2797
3238
  const line = rawLine.trim();
@@ -2802,21 +3243,35 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2802
3243
  } catch {
2803
3244
  continue;
2804
3245
  }
2805
- const evList = extractEventsFromTranscriptEntry(entry);
3246
+ const evList = extractEventsFromTranscriptEntry(entry, state.toolUsesBySession[sessionId]);
2806
3247
  for (const ev of evList) {
2807
3248
  if (ev.hook_event_name === "UserPromptSubmit" && ev.prompt) {
2808
3249
  state.lastPromptBySession[sessionId] = ev.prompt;
2809
3250
  }
3251
+ const toolNameLower = ev.tool_name ? String(ev.tool_name).toLowerCase() : "";
2810
3252
  if (
2811
- ev.hook_event_name === "PreToolUse" &&
2812
- ev.tool_name &&
2813
- HOOK_READ_ONLY_TOOLS.has(String(ev.tool_name).toLowerCase())
3253
+ (ev.hook_event_name === "PreToolUse" || ev.hook_event_name === "PostToolUse") &&
3254
+ toolNameLower &&
3255
+ (HOOK_READ_ONLY_TOOLS.has(toolNameLower) || toolNameLower.startsWith("mcp__ml-memory__"))
2814
3256
  ) {
2815
3257
  recordLocalHookDrop(estimateTokens(ev.text));
2816
3258
  continue;
2817
3259
  }
2818
- const deltaText = String(ev.text || "").trim().slice(0, 1024);
2819
- if (!deltaText || deltaText.length < 4) continue;
3260
+ let deltaText = String(ev.text || "").trim().slice(0, 1024);
3261
+ if (ev.hook_event_name === "PostToolUse" && deltaText.length < 4) {
3262
+ const fallbackCmd =
3263
+ ev.tool_input && typeof ev.tool_input === "object"
3264
+ ? ev.tool_input.command ||
3265
+ ev.tool_input.CommandLine ||
3266
+ ev.tool_input.file_path ||
3267
+ ev.tool_input.path ||
3268
+ ""
3269
+ : "";
3270
+ deltaText = String(deltaText || fallbackCmd || ev.tool_name || "ok")
3271
+ .trim()
3272
+ .slice(0, 1024);
3273
+ }
3274
+ if (!deltaText || (ev.hook_event_name !== "PostToolUse" && deltaText.length < 4)) continue;
2820
3275
  if (!opts.apiKey) continue;
2821
3276
 
2822
3277
  const promptContext = state.lastPromptBySession[sessionId] || deltaText;
@@ -2837,9 +3292,13 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2837
3292
  : {}),
2838
3293
  tool_name: ev.tool_name || null,
2839
3294
  tool_input: ev.tool_input || null,
3295
+ ...(ev.tool_response !== undefined && ev.tool_response !== null
3296
+ ? { tool_response: ev.tool_response }
3297
+ : {}),
2840
3298
  commit_writes: true,
2841
3299
  user_id: opts.userId || "default",
2842
3300
  project_id: projectId,
3301
+ ...(opts.runId ? { run_id: opts.runId } : {}),
2843
3302
  session_id: sessionId,
2844
3303
  ...(opts.redactPolicy ? { redact_policy: opts.redactPolicy } : {}),
2845
3304
  ...(opts.redactScope ? { redact_scope: opts.redactScope } : {}),
@@ -2848,6 +3307,14 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2848
3307
  processedEvents += 1;
2849
3308
  telem.conversation_tokens_processed = (telem.conversation_tokens_processed || 0) + rawTok;
2850
3309
  telem.events_processed = (telem.events_processed || 0) + 1;
3310
+ if (
3311
+ lastObservedVaultRevision > Number(state.lastSyncedVaultRevision || 0) &&
3312
+ !(resp && resp.should_write)
3313
+ ) {
3314
+ state.lastSyncedVaultRevision = lastObservedVaultRevision;
3315
+ await runSyncRulesCommand({ ...opts, silent: true });
3316
+ rulesResynced = true;
3317
+ }
2851
3318
 
2852
3319
  if (ev.hook_event_name === "UserPromptSubmit" && resp && resp.should_intervene) {
2853
3320
  const recalledIds =
@@ -2876,6 +3343,11 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2876
3343
  telem.memories_superseded = (telem.memories_superseded || 0) + 1;
2877
3344
  }
2878
3345
  await runSyncRulesCommand({ ...opts, silent: true });
3346
+ state.lastSyncedVaultRevision = Math.max(
3347
+ Number(state.lastSyncedVaultRevision || 0),
3348
+ lastObservedVaultRevision
3349
+ );
3350
+ rulesResynced = true;
2879
3351
  }
2880
3352
  if (isMidTurnBlock) {
2881
3353
  intervenedCount += 1;
@@ -2894,10 +3366,9 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2894
3366
  activeIntervention: resp.intervention_message,
2895
3367
  });
2896
3368
  try {
2897
- fs.writeFileSync(
3369
+ writePrivateRunFile(
2898
3370
  SANDBOX_INTERVENTION_PATH,
2899
- JSON.stringify(interventionRecord, null, 2) + "\n",
2900
- "utf8"
3371
+ JSON.stringify(interventionRecord, null, 2) + "\n"
2901
3372
  );
2902
3373
  } catch {
2903
3374
  // ignore
@@ -2907,11 +3378,27 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2907
3378
  const ellipsisToken =
2908
3379
  process.env.ELLIPSIS_API_TOKEN || process.env.ELLIPSIS_SESSION_TOKEN;
2909
3380
  const ellipsisBase = (
2910
- process.env.ELLIPSIS_API_URL || "https://api.ellipsis.dev"
3381
+ process.env.ELLIPSIS_API_BASE_URL ||
3382
+ process.env.ELLIPSIS_API_URL ||
3383
+ "https://api.ellipsis.dev"
2911
3384
  ).replace(/\/+$/, "");
2912
- if (ellipsisSessionId && ellipsisToken && !state.notifiedSessions[sessionId]) {
3385
+ state.notifiedRulesBySession = state.notifiedRulesBySession || {};
3386
+ const notifiedRuleSet = new Set(
3387
+ Array.isArray(state.notifiedRulesBySession[sessionId])
3388
+ ? state.notifiedRulesBySession[sessionId]
3389
+ : []
3390
+ );
3391
+ const ruleFingerprints =
3392
+ Array.isArray(resp.violated_memory_ids) && resp.violated_memory_ids.length > 0
3393
+ ? resp.violated_memory_ids.map(String)
3394
+ : [String(resp.intervention_message).slice(0, 120)];
3395
+ const hasNovelRule = ruleFingerprints.some((fp) => !notifiedRuleSet.has(fp));
3396
+ if (ellipsisSessionId && ellipsisToken && hasNovelRule) {
3397
+ for (const fp of ruleFingerprints) notifiedRuleSet.add(fp);
3398
+ state.notifiedRulesBySession[sessionId] = Array.from(notifiedRuleSet).slice(-64);
2913
3399
  state.notifiedSessions[sessionId] = true;
2914
3400
  try {
3401
+ const idempKey = `slashml_${String(ellipsisSessionId).slice(-16)}_${String(ruleFingerprints[0] || "rule").replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 32)}`;
2915
3402
  await fetch(`${ellipsisBase}/v1/sessions/${ellipsisSessionId}/messages`, {
2916
3403
  method: "POST",
2917
3404
  headers: {
@@ -2920,6 +3407,7 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2920
3407
  },
2921
3408
  body: JSON.stringify({
2922
3409
  message: resp.intervention_message,
3410
+ idempotency_key: idempKey,
2923
3411
  }),
2924
3412
  });
2925
3413
  } catch {
@@ -2939,8 +3427,21 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2939
3427
  }
2940
3428
  }
2941
3429
 
3430
+ if (processedEvents === 0 && opts.apiKey) {
3431
+ try {
3432
+ await apiRequest(opts, "GET", "/v1/memory/status");
3433
+ if (lastObservedVaultRevision > Number(state.lastSyncedVaultRevision || 0)) {
3434
+ state.lastSyncedVaultRevision = lastObservedVaultRevision;
3435
+ await runSyncRulesCommand({ ...opts, silent: true });
3436
+ rulesResynced = true;
3437
+ }
3438
+ } catch {
3439
+ // fail-open when status probe is unreachable
3440
+ }
3441
+ }
3442
+
2942
3443
  try {
2943
- fs.writeFileSync(SANDBOX_OFFSETS_PATH, JSON.stringify(state, null, 2) + "\n", "utf8");
3444
+ writePrivateRunFile(SANDBOX_OFFSETS_PATH, JSON.stringify(state, null, 2) + "\n");
2944
3445
  } catch {
2945
3446
  // ignore offset persistence error
2946
3447
  }
@@ -2950,12 +3451,28 @@ async function scanSandboxTranscriptsOnce(opts, state) {
2950
3451
  processed_events: processedEvents,
2951
3452
  memories_assimilated: assimilatedCount,
2952
3453
  interventions_triggered: intervenedCount,
3454
+ rules_resynced: rulesResynced,
3455
+ vault_revision: lastObservedVaultRevision,
2953
3456
  interventions,
2954
3457
  };
2955
3458
  }
2956
3459
 
2957
3460
  async function runWatchSandboxCommand(opts) {
2958
3461
  if (opts.isDaemon) {
3462
+ try {
3463
+ if (fs.existsSync(SANDBOX_PID_PATH)) {
3464
+ const prevPid = Number(String(fs.readFileSync(SANDBOX_PID_PATH, "utf8")).trim());
3465
+ if (Number.isInteger(prevPid) && prevPid > 1 && prevPid !== process.pid) {
3466
+ try {
3467
+ process.kill(prevPid, "SIGTERM");
3468
+ } catch {
3469
+ // ignore if previous daemon already exited
3470
+ }
3471
+ }
3472
+ }
3473
+ } catch {
3474
+ // ignore pid read error
3475
+ }
2959
3476
  const { spawn } = require("child_process");
2960
3477
  const forwarded = process.argv
2961
3478
  .slice(2)
@@ -2967,7 +3484,7 @@ async function runWatchSandboxCommand(opts) {
2967
3484
  });
2968
3485
  child.unref();
2969
3486
  try {
2970
- fs.writeFileSync(SANDBOX_PID_PATH, String(child.pid) + "\n", "utf8");
3487
+ writePrivateRunFile(SANDBOX_PID_PATH, String(child.pid) + "\n");
2971
3488
  } catch {
2972
3489
  // ignore
2973
3490
  }
@@ -2985,7 +3502,10 @@ async function runWatchSandboxCommand(opts) {
2985
3502
  offsets: {},
2986
3503
  lastPromptBySession: {},
2987
3504
  whisperedBySession: {},
3505
+ toolUsesBySession: {},
2988
3506
  notifiedSessions: {},
3507
+ notifiedRulesBySession: {},
3508
+ lastSyncedVaultRevision: 0,
2989
3509
  };
2990
3510
  if (fs.existsSync(SANDBOX_OFFSETS_PATH)) {
2991
3511
  try {
@@ -2995,7 +3515,10 @@ async function runWatchSandboxCommand(opts) {
2995
3515
  offsets: loaded.offsets || {},
2996
3516
  lastPromptBySession: loaded.lastPromptBySession || {},
2997
3517
  whisperedBySession: loaded.whisperedBySession || {},
3518
+ toolUsesBySession: loaded.toolUsesBySession || {},
2998
3519
  notifiedSessions: loaded.notifiedSessions || {},
3520
+ notifiedRulesBySession: loaded.notifiedRulesBySession || {},
3521
+ lastSyncedVaultRevision: Number(loaded.lastSyncedVaultRevision || 0),
2999
3522
  };
3000
3523
  }
3001
3524
  } catch {
@@ -3704,6 +4227,839 @@ async function runImportLocalCommand(opts) {
3704
4227
  }
3705
4228
  }
3706
4229
 
4230
+ const DEFAULT_GUARDED_SHELL_COMMANDS = [
4231
+ "psql",
4232
+ "mysql",
4233
+ "sqlite3",
4234
+ "redis-cli",
4235
+ "mongosh",
4236
+ "git",
4237
+ "gh",
4238
+ "rm",
4239
+ "mv",
4240
+ "kubectl",
4241
+ "helm",
4242
+ "terraform",
4243
+ "pulumi",
4244
+ "wrangler",
4245
+ "aws",
4246
+ "gcloud",
4247
+ "az",
4248
+ "stripe",
4249
+ "docker",
4250
+ "npm",
4251
+ "pnpm",
4252
+ "yarn",
4253
+ "pip",
4254
+ "uv",
4255
+ "curl",
4256
+ "wget",
4257
+ ];
4258
+
4259
+ function shellQuoteArg(val) {
4260
+ const s = String(val ?? "");
4261
+ if (!s) return "''";
4262
+ if (/^[a-zA-Z0-9_./:@=+-]+$/.test(s)) return s;
4263
+ return `'${s.replace(/'/g, "'\\''")}'`;
4264
+ }
4265
+
4266
+ async function runMintTokenCommand(opts) {
4267
+ const targetAgent = String(opts.agentId || "").trim();
4268
+ if (!targetAgent) {
4269
+ throw new Error("mint-token requires --agent <agent_id> (or SLASHML_AGENT_ID).");
4270
+ }
4271
+ const payload = {
4272
+ authority_tier: opts.tokenTier || "worker",
4273
+ ttl_seconds: Number(opts.ttlSeconds || 3600),
4274
+ can_delegate: Boolean(opts.canDelegate),
4275
+ };
4276
+ if (opts.runId) payload.run_id = opts.runId;
4277
+ if (opts.projectId) payload.project_id = opts.projectId;
4278
+ if (opts.explicitUserId) payload.user_id = opts.explicitUserId;
4279
+ if (opts.accessMode) payload.access_mode = opts.accessMode;
4280
+ if (opts.redactPolicy) {
4281
+ payload.redact_policy = opts.redactPolicy.includes(",")
4282
+ ? opts.redactPolicy
4283
+ .split(",")
4284
+ .map((s) => s.trim())
4285
+ .filter(Boolean)
4286
+ : opts.redactPolicy;
4287
+ }
4288
+ if (opts.redactScope) payload.redact_scope = opts.redactScope;
4289
+
4290
+ const mintOpts = { ...opts, agentId: null };
4291
+ const res = await apiRequest(
4292
+ mintOpts,
4293
+ "POST",
4294
+ `/v1/agents/${encodeURIComponent(targetAgent)}/tokens`,
4295
+ payload
4296
+ );
4297
+
4298
+ if (opts.printEnv) {
4299
+ const lines = [
4300
+ `export SLASHML_API_KEY=${shellQuoteArg(res.token)}`,
4301
+ `export SLASHML_AGENT_ID=${shellQuoteArg(targetAgent)}`,
4302
+ ];
4303
+ const resolvedRunId =
4304
+ res.run_id || (res.claims && (res.claims.rid || res.claims.run)) || opts.runId;
4305
+ if (resolvedRunId) {
4306
+ lines.push(`export SLASHML_RUN_ID=${shellQuoteArg(resolvedRunId)}`);
4307
+ }
4308
+ const resolvedProjectId =
4309
+ res.project_id || (res.claims && res.claims.prj) || opts.projectId;
4310
+ if (resolvedProjectId) {
4311
+ lines.push(`export SLASHML_PROJECT_ID=${shellQuoteArg(resolvedProjectId)}`);
4312
+ }
4313
+ process.stdout.write(lines.join("\n") + "\n");
4314
+ return res;
4315
+ }
4316
+ if (opts.jsonOutput) {
4317
+ process.stdout.write(JSON.stringify(res, null, 2) + "\n");
4318
+ } else {
4319
+ process.stdout.write(`${res.token}\n`);
4320
+ }
4321
+ return res;
4322
+ }
4323
+
4324
+ async function runRevokeTokenCommand(opts) {
4325
+ const revokeOpts = { ...opts, agentId: null };
4326
+ let res;
4327
+ if (opts.revokeAll) {
4328
+ res = await apiRequest(revokeOpts, "POST", "/v1/agents/revoke-all", {});
4329
+ } else {
4330
+ const targetAgent = String(opts.agentId || "").trim();
4331
+ if (!targetAgent) {
4332
+ throw new Error("revoke-token requires --agent <agent_id> or --all.");
4333
+ }
4334
+ res = await apiRequest(
4335
+ revokeOpts,
4336
+ "POST",
4337
+ `/v1/agents/${encodeURIComponent(targetAgent)}/revoke`,
4338
+ {}
4339
+ );
4340
+ }
4341
+ if (opts.jsonOutput) {
4342
+ process.stdout.write(JSON.stringify(res, null, 2) + "\n");
4343
+ } else if (opts.revokeAll) {
4344
+ console.log("[/ ml] Revoked all delegated swarm tokens in workspace.");
4345
+ } else {
4346
+ console.log(`[/ ml] Revoked delegated swarm tokens for agent '${res.agent_id}'.`);
4347
+ }
4348
+ return res;
4349
+ }
4350
+
4351
+ async function runPromoteCommand(opts) {
4352
+ if (!opts.runId) {
4353
+ throw new Error("promote requires --run <run_id> (or SLASHML_RUN_ID).");
4354
+ }
4355
+ const payload = {
4356
+ run_id: opts.runId,
4357
+ discard_unpromoted: Boolean(opts.discardUnpromoted),
4358
+ };
4359
+ if (opts.projectId) payload.target_project_id = opts.projectId;
4360
+ if (opts.explicitUserId) payload.target_user_id = opts.explicitUserId;
4361
+ if (Array.isArray(opts.promoteMemoryIds) && opts.promoteMemoryIds.length > 0) {
4362
+ payload.memory_ids = opts.promoteMemoryIds;
4363
+ }
4364
+ const res = await apiRequest(opts, "POST", "/v1/memory/promote", payload);
4365
+ if (opts.jsonOutput) {
4366
+ process.stdout.write(JSON.stringify(res, null, 2) + "\n");
4367
+ } else {
4368
+ console.log(
4369
+ `[/ ml] Promoted ${res.promoted_count || 0} memory record(s) from run '${opts.runId}' (discarded=${res.discarded_count || 0}).`
4370
+ );
4371
+ }
4372
+ return res;
4373
+ }
4374
+
4375
+ function runInstallShellGuardsCommand(opts) {
4376
+ const binDir = path.resolve(opts.guardBinDir || "/tmp/.slashml-guards/bin");
4377
+ fs.mkdirSync(binDir, { recursive: true, mode: 0o755 });
4378
+ const rawCommands =
4379
+ Array.isArray(opts.guardCommands) && opts.guardCommands.length > 0
4380
+ ? opts.guardCommands
4381
+ : DEFAULT_GUARDED_SHELL_COMMANDS;
4382
+ const installed = [];
4383
+ const nodeBin = process.execPath;
4384
+ const selfScript = path.resolve(__filename);
4385
+
4386
+ for (const rawCmd of rawCommands) {
4387
+ const cmd = String(rawCmd || "").trim();
4388
+ if (!cmd || !/^[a-zA-Z0-9._+-]+$/.test(cmd)) continue;
4389
+ const shimPath = path.join(binDir, cmd);
4390
+ const shimBody = [
4391
+ "#!/bin/sh",
4392
+ `SLASHML_GUARD_SELF_DIR=${shellQuoteArg(binDir)} exec ${shellQuoteArg(nodeBin)} ${shellQuoteArg(selfScript)} guard-exec -- ${shellQuoteArg(cmd)} "$@"`,
4393
+ "",
4394
+ ].join("\n");
4395
+ fs.writeFileSync(shimPath, shimBody, { encoding: "utf8", mode: 0o755 });
4396
+ try {
4397
+ fs.chmodSync(shimPath, 0o755);
4398
+ } catch {}
4399
+ installed.push(cmd);
4400
+ }
4401
+
4402
+ const exportLine = `export PATH=${shellQuoteArg(binDir)}:"$PATH"`;
4403
+ if (opts.profilePath) {
4404
+ const prof = path.resolve(opts.profilePath);
4405
+ let existing = "";
4406
+ if (fs.existsSync(prof)) {
4407
+ try {
4408
+ existing = fs.readFileSync(prof, "utf8");
4409
+ } catch {}
4410
+ }
4411
+ if (!existing.includes(binDir)) {
4412
+ const next = existing ? `${existing.replace(/\n*$/, "")}\n${exportLine}\n` : `${exportLine}\n`;
4413
+ fs.mkdirSync(path.dirname(prof), { recursive: true });
4414
+ fs.writeFileSync(prof, next, "utf8");
4415
+ }
4416
+ }
4417
+
4418
+ const payload = {
4419
+ status: "installed",
4420
+ bin_dir: binDir,
4421
+ commands: installed,
4422
+ installed_count: installed.length,
4423
+ path_export: exportLine,
4424
+ };
4425
+ if (opts.printEnv) {
4426
+ process.stdout.write(`${exportLine}\n`);
4427
+ } else if (opts.jsonOutput) {
4428
+ process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
4429
+ } else {
4430
+ console.log(
4431
+ `[/ ml] Installed ${installed.length} shell guardrail shims in ${binDir}.\nActivate in your shell or Dockerfile:\n ${exportLine}`
4432
+ );
4433
+ }
4434
+ return payload;
4435
+ }
4436
+
4437
+ function isReadOnlyGuardExecCommand(cmdName, cmdArgs) {
4438
+ const base = path.basename(String(cmdName || "")).toLowerCase();
4439
+ const args = Array.isArray(cmdArgs) ? cmdArgs.map((a) => String(a)) : [];
4440
+ if (
4441
+ args.length === 1 &&
4442
+ (args[0] === "--version" || args[0] === "-v" || args[0] === "--help" || args[0] === "-h")
4443
+ ) {
4444
+ return true;
4445
+ }
4446
+ if (base === "git") {
4447
+ let idx = 0;
4448
+ while (idx < args.length) {
4449
+ const tok = args[idx];
4450
+ if (tok === "-C" || tok === "-c" || tok === "--git-dir" || tok === "--work-tree") {
4451
+ idx += 2;
4452
+ continue;
4453
+ }
4454
+ if (tok.startsWith("-")) {
4455
+ idx += 1;
4456
+ continue;
4457
+ }
4458
+ break;
4459
+ }
4460
+ const sub = (args[idx] || "").toLowerCase();
4461
+ const rest = args.slice(idx + 1);
4462
+ if (
4463
+ sub === "status" ||
4464
+ sub === "diff" ||
4465
+ sub === "log" ||
4466
+ sub === "show" ||
4467
+ sub === "rev-parse" ||
4468
+ sub === "ls-files" ||
4469
+ sub === "describe" ||
4470
+ sub === "blame"
4471
+ ) {
4472
+ return true;
4473
+ }
4474
+ if (sub === "branch") {
4475
+ return !rest.some((r) => /^-(d|D|m|M|c|C)$|^--delete$|^--move$/.test(r));
4476
+ }
4477
+ if (sub === "remote") {
4478
+ return rest.length === 0 || (rest.length === 1 && rest[0] === "-v") || rest[0] === "get-url";
4479
+ }
4480
+ return false;
4481
+ }
4482
+ if (base === "kubectl") {
4483
+ const firstNonFlag = args.find((a) => !a.startsWith("-")) || "";
4484
+ return ["get", "describe", "logs", "version", "api-resources", "explain"].includes(
4485
+ firstNonFlag.toLowerCase()
4486
+ );
4487
+ }
4488
+ if (base === "aws") {
4489
+ const positional = args.filter((a) => !a.startsWith("-"));
4490
+ return positional[0] === "sts" && positional[1] === "get-caller-identity";
4491
+ }
4492
+ if (base === "docker") {
4493
+ const firstNonFlag = (args.find((a) => !a.startsWith("-")) || "").toLowerCase();
4494
+ return ["ps", "images", "inspect", "logs", "version", "info"].includes(firstNonFlag);
4495
+ }
4496
+ return false;
4497
+ }
4498
+
4499
+ function resolveRealBinaryPath(cmdName, excludedDirs) {
4500
+ const excluded = new Set(
4501
+ (excludedDirs || [])
4502
+ .filter(Boolean)
4503
+ .map((d) => {
4504
+ try {
4505
+ return fs.realpathSync(path.resolve(d));
4506
+ } catch {
4507
+ return path.resolve(d);
4508
+ }
4509
+ })
4510
+ );
4511
+ if (cmdName.includes("/") || cmdName.includes(path.sep)) {
4512
+ const resolved = path.resolve(cmdName);
4513
+ const dir = path.dirname(resolved);
4514
+ let realDir = dir;
4515
+ try {
4516
+ realDir = fs.realpathSync(dir);
4517
+ } catch {}
4518
+ if (!excluded.has(dir) && !excluded.has(realDir) && fs.existsSync(resolved)) {
4519
+ return resolved;
4520
+ }
4521
+ return null;
4522
+ }
4523
+ const pathEnv = process.env.PATH || "";
4524
+ const segments = pathEnv.split(path.delimiter).filter(Boolean);
4525
+ for (const seg of segments) {
4526
+ const absSeg = path.resolve(seg);
4527
+ let realSeg = absSeg;
4528
+ try {
4529
+ realSeg = fs.realpathSync(absSeg);
4530
+ } catch {}
4531
+ if (excluded.has(absSeg) || excluded.has(realSeg)) continue;
4532
+ const candidate = path.join(absSeg, cmdName);
4533
+ try {
4534
+ const st = fs.statSync(candidate);
4535
+ if (st.isFile()) {
4536
+ fs.accessSync(candidate, fs.constants.X_OK);
4537
+ return candidate;
4538
+ }
4539
+ } catch {
4540
+ continue;
4541
+ }
4542
+ }
4543
+ return null;
4544
+ }
4545
+
4546
+ function formatGuardBlockBanner(rawMessage) {
4547
+ const msg = String(rawMessage || "Action blocked by SlashML workspace guardrail.").trim();
4548
+ if (msg.includes("[SLASHML GUARDRAIL BLOCK]")) return msg;
4549
+ return `[SLASHML GUARDRAIL BLOCK] ${msg}`;
4550
+ }
4551
+
4552
+ async function evaluateGuardrailPreToolUse(opts, toolName, toolInput, summaryText, timeoutMs) {
4553
+ if (!opts.apiKey) {
4554
+ if (opts.failMode === "closed") {
4555
+ return {
4556
+ blocked: true,
4557
+ message: "[SLASHML GUARDRAIL BLOCK] SLASHML_API_KEY missing in fail-closed guardrail mode.",
4558
+ };
4559
+ }
4560
+ return { blocked: false };
4561
+ }
4562
+ const controller = new AbortController();
4563
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
4564
+ try {
4565
+ const headers = {
4566
+ Authorization: `Bearer ${opts.apiKey}`,
4567
+ "Content-Type": "application/json",
4568
+ "User-Agent": `slashml-guard/${PACKAGE_VERSION}`,
4569
+ };
4570
+ if (opts.agentId) headers["X-SlashML-Agent-Id"] = opts.agentId;
4571
+ if (opts.runId) headers["X-SlashML-Run-Id"] = opts.runId;
4572
+ if (opts.projectId) headers["X-SlashML-Project-Id"] = opts.projectId;
4573
+ const body = {
4574
+ hook_event_name: "PreToolUse",
4575
+ strict_pretool_block: true,
4576
+ prompt: summaryText,
4577
+ text: summaryText,
4578
+ tool_name: toolName,
4579
+ tool_input: toolInput,
4580
+ commit_writes: false,
4581
+ user_id: opts.userId || "default",
4582
+ ...(opts.projectId ? { project_id: opts.projectId } : {}),
4583
+ ...(opts.runId ? { run_id: opts.runId } : {}),
4584
+ ...(opts.agentId ? { caller_agent_id: opts.agentId } : {}),
4585
+ ...(opts.redactPolicy ? { redact_policy: opts.redactPolicy } : {}),
4586
+ ...(opts.redactScope ? { redact_scope: opts.redactScope } : {}),
4587
+ };
4588
+ const res = await fetch(`${opts.baseUrl}/v1/memory/intervene`, {
4589
+ method: "POST",
4590
+ headers,
4591
+ body: JSON.stringify(body),
4592
+ signal: controller.signal,
4593
+ });
4594
+ updateObservedVaultRevisionFromResponse(res);
4595
+ const raw = await res.text();
4596
+ let data = {};
4597
+ try {
4598
+ data = raw ? JSON.parse(raw) : {};
4599
+ } catch {
4600
+ data = {};
4601
+ }
4602
+ if (res.status === 401 || res.status === 403) {
4603
+ const detail = data.detail || data.error || `HTTP ${res.status}`;
4604
+ return {
4605
+ blocked: true,
4606
+ message: formatGuardBlockBanner(`Agent credential rejected: ${detail}`),
4607
+ };
4608
+ }
4609
+ if (!res.ok) {
4610
+ if (opts.failMode === "closed") {
4611
+ return {
4612
+ blocked: true,
4613
+ message: formatGuardBlockBanner(`Guardrail service returned HTTP ${res.status}.`),
4614
+ };
4615
+ }
4616
+ return { blocked: false };
4617
+ }
4618
+ const hookEnv = data && typeof data.hook_output === "object" ? data.hook_output : data;
4619
+ const hookOut =
4620
+ hookEnv && typeof hookEnv.hookSpecificOutput === "object"
4621
+ ? hookEnv.hookSpecificOutput
4622
+ : data && typeof data.hookSpecificOutput === "object"
4623
+ ? data.hookSpecificOutput
4624
+ : null;
4625
+ const permDec = hookOut ? String(hookOut.permissionDecision || "").toLowerCase() : "";
4626
+ const isBlocked =
4627
+ data &&
4628
+ (data.intervention_severity === "BLOCK" ||
4629
+ data.action === "BLOCK" ||
4630
+ data.decision === "BLOCK" ||
4631
+ permDec === "deny");
4632
+ if (isBlocked) {
4633
+ const msgText =
4634
+ data.intervention_message ||
4635
+ (hookOut && hookOut.permissionDecisionReason) ||
4636
+ data.whisper ||
4637
+ "";
4638
+ return {
4639
+ blocked: true,
4640
+ message: formatGuardBlockBanner(msgText),
4641
+ violated_memory_ids: data.violated_memory_ids || data.whispered_memory_ids || [],
4642
+ };
4643
+ }
4644
+ return { blocked: false, response: data };
4645
+ } catch (err) {
4646
+ if (opts.failMode === "closed") {
4647
+ return {
4648
+ blocked: true,
4649
+ message: formatGuardBlockBanner(
4650
+ `Guardrail check unreachable in fail-closed mode: ${err.message || err}`
4651
+ ),
4652
+ };
4653
+ }
4654
+ return { blocked: false };
4655
+ } finally {
4656
+ clearTimeout(timer);
4657
+ }
4658
+ }
4659
+
4660
+ async function redactTextViaGuardrail(opts, text, timeoutMs = 4000) {
4661
+ if (!opts.apiKey || !text || !String(text).trim()) return text;
4662
+ const shouldRun =
4663
+ (opts.redactPolicy && opts.redactPolicy !== "off") ||
4664
+ String(opts.apiKey).startsWith("sml_st_");
4665
+ if (!shouldRun) return text;
4666
+ const controller = new AbortController();
4667
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
4668
+ try {
4669
+ const headers = {
4670
+ Authorization: `Bearer ${opts.apiKey}`,
4671
+ "Content-Type": "application/json",
4672
+ "User-Agent": `slashml-guard/${PACKAGE_VERSION}`,
4673
+ };
4674
+ if (opts.agentId) headers["X-SlashML-Agent-Id"] = opts.agentId;
4675
+ if (opts.runId) headers["X-SlashML-Run-Id"] = opts.runId;
4676
+ if (opts.projectId) headers["X-SlashML-Project-Id"] = opts.projectId;
4677
+ const payload = {
4678
+ text: String(text),
4679
+ ...(opts.redactPolicy ? { redact_policy: opts.redactPolicy } : {}),
4680
+ };
4681
+ const res = await fetch(`${opts.baseUrl}/v1/memory/redact`, {
4682
+ method: "POST",
4683
+ headers,
4684
+ body: JSON.stringify(payload),
4685
+ signal: controller.signal,
4686
+ });
4687
+ updateObservedVaultRevisionFromResponse(res);
4688
+ if (!res.ok) return text;
4689
+ const data = await res.json();
4690
+ if (data && typeof data.redacted_text === "string") {
4691
+ return data.redacted_text;
4692
+ }
4693
+ return text;
4694
+ } catch {
4695
+ return text;
4696
+ } finally {
4697
+ clearTimeout(timer);
4698
+ }
4699
+ }
4700
+
4701
+ async function runGuardExecCommand(opts) {
4702
+ const argv = Array.isArray(opts.guardExecArgv) ? opts.guardExecArgv : [];
4703
+ if (argv.length === 0) {
4704
+ process.stderr.write("Usage: slashml-memory guard-exec [options] -- <command> [args...]\n");
4705
+ return 2;
4706
+ }
4707
+ const [cmdName, ...cmdArgs] = argv;
4708
+ const excludedDirs = [
4709
+ process.env.SLASHML_GUARD_SELF_DIR,
4710
+ opts.guardBinDir,
4711
+ process.env.SLASHML_GUARD_BIN_DIR,
4712
+ "/tmp/.slashml-guards/bin",
4713
+ ];
4714
+
4715
+ if (!isReadOnlyGuardExecCommand(cmdName, cmdArgs)) {
4716
+ const fullCmd = [cmdName, ...cmdArgs].map(shellQuoteArg).join(" ");
4717
+ const timeoutMs =
4718
+ opts.guardTimeoutMs || Math.max(100, Number(process.env.SLASHML_GUARD_TIMEOUT_MS || 1500));
4719
+ const check = await evaluateGuardrailPreToolUse(
4720
+ opts,
4721
+ "Bash",
4722
+ { command: fullCmd, binary: cmdName, argv: cmdArgs },
4723
+ fullCmd,
4724
+ timeoutMs
4725
+ );
4726
+ if (check.blocked) {
4727
+ process.stderr.write(`${check.message}\n`);
4728
+ return 126;
4729
+ }
4730
+ }
4731
+
4732
+ const realBin = resolveRealBinaryPath(cmdName, excludedDirs);
4733
+ if (!realBin) {
4734
+ process.stderr.write(`${cmdName}: command not found\n`);
4735
+ return 127;
4736
+ }
4737
+ const { spawnSync } = require("child_process");
4738
+ const cleanPath = (process.env.PATH || "")
4739
+ .split(path.delimiter)
4740
+ .filter((seg) => {
4741
+ if (!seg) return false;
4742
+ const abs = path.resolve(seg);
4743
+ return abs !== path.resolve(process.env.SLASHML_GUARD_SELF_DIR || "\0");
4744
+ })
4745
+ .join(path.delimiter);
4746
+ const childRes = spawnSync(realBin, cmdArgs, {
4747
+ stdio: "inherit",
4748
+ env: { ...process.env, PATH: cleanPath },
4749
+ });
4750
+ if (childRes.error) {
4751
+ process.stderr.write(`${cmdName}: ${childRes.error.message}\n`);
4752
+ return 127;
4753
+ }
4754
+ if (typeof childRes.status === "number") {
4755
+ return childRes.status;
4756
+ }
4757
+ return 1;
4758
+ }
4759
+
4760
+ async function scrubMcpResponseContent(opts, respMsg, timeoutMs) {
4761
+ if (
4762
+ !respMsg ||
4763
+ typeof respMsg !== "object" ||
4764
+ !respMsg.result ||
4765
+ !Array.isArray(respMsg.result.content)
4766
+ ) {
4767
+ return respMsg;
4768
+ }
4769
+ for (const block of respMsg.result.content) {
4770
+ if (block && block.type === "text" && typeof block.text === "string" && block.text.trim()) {
4771
+ block.text = await redactTextViaGuardrail(opts, block.text, timeoutMs);
4772
+ }
4773
+ }
4774
+ return respMsg;
4775
+ }
4776
+
4777
+ async function runWrapMcpCommand(opts) {
4778
+ const timeoutMs =
4779
+ opts.guardTimeoutMs || Math.max(250, Number(process.env.SLASHML_GUARD_TIMEOUT_MS || 5000));
4780
+
4781
+ if (opts.upstreamUrl) {
4782
+ const clientRl = readline.createInterface({ input: process.stdin, terminal: false });
4783
+ let chain = Promise.resolve();
4784
+ let upstreamSessionId = null;
4785
+ clientRl.on("line", (rawLine) => {
4786
+ const trimmed = rawLine.trim();
4787
+ if (!trimmed) return;
4788
+ chain = chain.then(async () => {
4789
+ let msg;
4790
+ try {
4791
+ msg = JSON.parse(trimmed);
4792
+ } catch {
4793
+ return;
4794
+ }
4795
+ if (msg && msg.method === "tools/call") {
4796
+ const toolName = String((msg.params && msg.params.name) || "");
4797
+ const toolArgs = (msg.params && msg.params.arguments) || {};
4798
+ const summary = `${toolName} ${JSON.stringify(toolArgs)}`;
4799
+ const check = await evaluateGuardrailPreToolUse(
4800
+ opts,
4801
+ toolName,
4802
+ toolArgs,
4803
+ summary,
4804
+ timeoutMs
4805
+ );
4806
+ if (check.blocked) {
4807
+ process.stdout.write(
4808
+ JSON.stringify({
4809
+ jsonrpc: "2.0",
4810
+ id: msg.id,
4811
+ result: {
4812
+ isError: true,
4813
+ content: [{ type: "text", text: check.message }],
4814
+ },
4815
+ }) + "\n"
4816
+ );
4817
+ return;
4818
+ }
4819
+ }
4820
+ try {
4821
+ const headers = {
4822
+ "Content-Type": "application/json",
4823
+ Accept: "application/json",
4824
+ };
4825
+ if (upstreamSessionId) headers["Mcp-Session-Id"] = upstreamSessionId;
4826
+ const upRes = await fetch(opts.upstreamUrl, {
4827
+ method: "POST",
4828
+ headers,
4829
+ body: JSON.stringify(msg),
4830
+ });
4831
+ const sid = upRes.headers.get("mcp-session-id");
4832
+ if (sid) upstreamSessionId = sid;
4833
+ if (upRes.status === 202 || msg.id === undefined || msg.id === null) {
4834
+ return;
4835
+ }
4836
+ let respMsg = await upRes.json();
4837
+ if (msg && msg.method === "tools/call") {
4838
+ respMsg = await scrubMcpResponseContent(opts, respMsg, timeoutMs);
4839
+ }
4840
+ process.stdout.write(JSON.stringify(respMsg) + "\n");
4841
+ } catch (err) {
4842
+ if (msg && msg.id !== undefined && msg.id !== null) {
4843
+ process.stdout.write(
4844
+ JSON.stringify({
4845
+ jsonrpc: "2.0",
4846
+ id: msg.id,
4847
+ error: { code: -32603, message: `Upstream MCP error: ${err.message || err}` },
4848
+ }) + "\n"
4849
+ );
4850
+ }
4851
+ }
4852
+ });
4853
+ });
4854
+ await new Promise((resolve) => {
4855
+ clientRl.on("close", () => {
4856
+ chain.then(resolve).catch(resolve);
4857
+ });
4858
+ });
4859
+ return;
4860
+ }
4861
+
4862
+ let cmdBin = null;
4863
+ let cmdArgs = [];
4864
+ let useShell = false;
4865
+ if (Array.isArray(opts.wrapArgv) && opts.wrapArgv.length > 0) {
4866
+ [cmdBin, ...cmdArgs] = opts.wrapArgv;
4867
+ } else if (opts.upstreamCmd && String(opts.upstreamCmd).trim()) {
4868
+ cmdBin = String(opts.upstreamCmd).trim();
4869
+ useShell = true;
4870
+ } else {
4871
+ throw new Error(
4872
+ "wrap-mcp requires an upstream command (`slashml-memory wrap-mcp -- <cmd> [args...]`) or `--upstream-url <url>`."
4873
+ );
4874
+ }
4875
+
4876
+ const { spawn } = require("child_process");
4877
+ const child = spawn(cmdBin, cmdArgs, {
4878
+ stdio: ["pipe", "pipe", "inherit"],
4879
+ env: process.env,
4880
+ shell: useShell,
4881
+ });
4882
+
4883
+ const pendingToolCalls = new Map();
4884
+ let inFlightRequests = 0;
4885
+ let stdinClosed = false;
4886
+ let childExited = false;
4887
+
4888
+ function maybeCloseChildStdin() {
4889
+ if (stdinClosed && inFlightRequests <= 0 && !childExited) {
4890
+ try {
4891
+ child.stdin.end();
4892
+ } catch {}
4893
+ }
4894
+ }
4895
+
4896
+ const childRl = readline.createInterface({ input: child.stdout, terminal: false });
4897
+ let outChain = Promise.resolve();
4898
+ childRl.on("line", (rawLine) => {
4899
+ const trimmed = rawLine.trim();
4900
+ if (!trimmed) return;
4901
+ outChain = outChain.then(async () => {
4902
+ let respMsg;
4903
+ try {
4904
+ respMsg = JSON.parse(trimmed);
4905
+ } catch {
4906
+ process.stdout.write(rawLine + "\n");
4907
+ return;
4908
+ }
4909
+ const hasId = respMsg && respMsg.id !== undefined && respMsg.id !== null;
4910
+ if (hasId) {
4911
+ const idKey = String(respMsg.id);
4912
+ if (pendingToolCalls.has(idKey)) {
4913
+ pendingToolCalls.delete(idKey);
4914
+ respMsg = await scrubMcpResponseContent(opts, respMsg, timeoutMs);
4915
+ }
4916
+ inFlightRequests = Math.max(0, inFlightRequests - 1);
4917
+ }
4918
+ process.stdout.write(JSON.stringify(respMsg) + "\n");
4919
+ if (hasId) {
4920
+ maybeCloseChildStdin();
4921
+ }
4922
+ });
4923
+ });
4924
+
4925
+ const clientRl = readline.createInterface({ input: process.stdin, terminal: false });
4926
+ let inChain = Promise.resolve();
4927
+ clientRl.on("line", (rawLine) => {
4928
+ const trimmed = rawLine.trim();
4929
+ if (!trimmed) return;
4930
+ inChain = inChain.then(async () => {
4931
+ let msg;
4932
+ try {
4933
+ msg = JSON.parse(trimmed);
4934
+ } catch {
4935
+ if (!childExited) {
4936
+ child.stdin.write(rawLine + "\n");
4937
+ }
4938
+ return;
4939
+ }
4940
+ if (msg && msg.method === "tools/call") {
4941
+ const toolName = String((msg.params && msg.params.name) || "");
4942
+ const toolArgs = (msg.params && msg.params.arguments) || {};
4943
+ const summary = `${toolName} ${JSON.stringify(toolArgs)}`;
4944
+ const check = await evaluateGuardrailPreToolUse(
4945
+ opts,
4946
+ toolName,
4947
+ toolArgs,
4948
+ summary,
4949
+ timeoutMs
4950
+ );
4951
+ if (check.blocked) {
4952
+ if (msg.id !== undefined && msg.id !== null) {
4953
+ process.stdout.write(
4954
+ JSON.stringify({
4955
+ jsonrpc: "2.0",
4956
+ id: msg.id,
4957
+ result: {
4958
+ isError: true,
4959
+ content: [{ type: "text", text: check.message }],
4960
+ },
4961
+ }) + "\n"
4962
+ );
4963
+ }
4964
+ maybeCloseChildStdin();
4965
+ return;
4966
+ }
4967
+ if (msg.id !== undefined && msg.id !== null) {
4968
+ pendingToolCalls.set(String(msg.id), { toolName });
4969
+ }
4970
+ }
4971
+ if (msg && msg.id !== undefined && msg.id !== null) {
4972
+ inFlightRequests += 1;
4973
+ }
4974
+ if (!childExited) {
4975
+ child.stdin.write(JSON.stringify(msg) + "\n");
4976
+ }
4977
+ });
4978
+ });
4979
+
4980
+ clientRl.on("close", () => {
4981
+ inChain
4982
+ .then(() => {
4983
+ stdinClosed = true;
4984
+ maybeCloseChildStdin();
4985
+ })
4986
+ .catch(() => {
4987
+ stdinClosed = true;
4988
+ maybeCloseChildStdin();
4989
+ });
4990
+ });
4991
+
4992
+ const exitCode = await new Promise((resolve, reject) => {
4993
+ child.on("error", reject);
4994
+ child.on("close", (code) => {
4995
+ childExited = true;
4996
+ outChain.then(() => resolve(code || 0)).catch(() => resolve(code || 0));
4997
+ });
4998
+ });
4999
+ process.exitCode = exitCode;
5000
+ }
5001
+
5002
+ if (parsed.isMintToken) {
5003
+ runMintTokenCommand(parsed)
5004
+ .then(() => process.exit(0))
5005
+ .catch((err) => {
5006
+ console.error(`Error: ${err.message || err}`);
5007
+ process.exit(1);
5008
+ });
5009
+ return;
5010
+ }
5011
+
5012
+ if (parsed.isRevokeToken) {
5013
+ runRevokeTokenCommand(parsed)
5014
+ .then(() => process.exit(0))
5015
+ .catch((err) => {
5016
+ console.error(`Error: ${err.message || err}`);
5017
+ process.exit(1);
5018
+ });
5019
+ return;
5020
+ }
5021
+
5022
+ if (parsed.isPromote) {
5023
+ runPromoteCommand(parsed)
5024
+ .then(() => process.exit(0))
5025
+ .catch((err) => {
5026
+ console.error(`Error: ${err.message || err}`);
5027
+ process.exit(1);
5028
+ });
5029
+ return;
5030
+ }
5031
+
5032
+ if (parsed.isInstallShellGuards) {
5033
+ try {
5034
+ runInstallShellGuardsCommand(parsed);
5035
+ process.exit(0);
5036
+ } catch (err) {
5037
+ console.error(`Error: ${err.message || err}`);
5038
+ process.exit(1);
5039
+ }
5040
+ return;
5041
+ }
5042
+
5043
+ if (parsed.isGuardExec) {
5044
+ runGuardExecCommand(parsed)
5045
+ .then((code) => process.exit(typeof code === "number" ? code : 0))
5046
+ .catch((err) => {
5047
+ console.error(`Error: ${err.message || err}`);
5048
+ process.exit(1);
5049
+ });
5050
+ return;
5051
+ }
5052
+
5053
+ if (parsed.isWrapMcp) {
5054
+ runWrapMcpCommand(parsed)
5055
+ .then(() => process.exit(process.exitCode || 0))
5056
+ .catch((err) => {
5057
+ console.error(`Error: ${err.message || err}`);
5058
+ process.exit(1);
5059
+ });
5060
+ return;
5061
+ }
5062
+
3707
5063
  if (parsed.isMigrate) {
3708
5064
  runMigrateCommand(parsed)
3709
5065
  .then(() => process.exit(0))
@@ -4395,11 +5751,18 @@ async function apiRequest(opts, method, urlPath, body) {
4395
5751
  if (opts.agentId) {
4396
5752
  headers["X-SlashML-Agent-Id"] = opts.agentId;
4397
5753
  }
5754
+ if (opts.runId) {
5755
+ headers["X-SlashML-Run-Id"] = opts.runId;
5756
+ }
5757
+ if (opts.projectId) {
5758
+ headers["X-SlashML-Project-Id"] = opts.projectId;
5759
+ }
4398
5760
  const res = await fetch(`${opts.baseUrl}${urlPath}`, {
4399
5761
  method,
4400
5762
  headers,
4401
5763
  body: body !== undefined ? JSON.stringify(body) : undefined,
4402
5764
  });
5765
+ updateObservedVaultRevisionFromResponse(res);
4403
5766
  const text = await res.text();
4404
5767
  const data = text ? JSON.parse(text) : {};
4405
5768
  if (!res.ok) {
@@ -4564,11 +5927,20 @@ async function dispatchTool(opts, name, args = {}) {
4564
5927
  const effRedactPolicy = args.redact_policy !== undefined ? args.redact_policy : opts.redactPolicy;
4565
5928
  const effRedactScope = args.redact_scope !== undefined ? args.redact_scope : opts.redactScope;
4566
5929
  const effAgentId = args.caller_agent_id || opts.agentId || null;
5930
+ const effRunId = args.run_id || opts.runId || null;
5931
+ const effProjectId = args.project_id || opts.projectId || null;
5932
+ const effInheritScopes =
5933
+ typeof args.inherit_scopes === "boolean" ? args.inherit_scopes : undefined;
4567
5934
 
4568
5935
  function withLifecycle(payload) {
4569
5936
  if (effRedactPolicy) payload.redact_policy = effRedactPolicy;
4570
5937
  if (effRedactScope) payload.redact_scope = effRedactScope;
4571
5938
  if (effAgentId) payload.caller_agent_id = effAgentId;
5939
+ if (effRunId && payload.run_id === undefined) payload.run_id = effRunId;
5940
+ if (effProjectId && payload.project_id === undefined) payload.project_id = effProjectId;
5941
+ if (effInheritScopes !== undefined && payload.inherit_scopes === undefined) {
5942
+ payload.inherit_scopes = effInheritScopes;
5943
+ }
4572
5944
  return payload;
4573
5945
  }
4574
5946
 
@@ -4618,6 +5990,11 @@ async function dispatchTool(opts, name, args = {}) {
4618
5990
  }
4619
5991
  if (name === "get_memories") {
4620
5992
  const paramsObj = { user_id: uid, limit: String(args.limit || 50) };
5993
+ if (effRunId) paramsObj.run_id = String(effRunId);
5994
+ if (effProjectId) paramsObj.project_id = String(effProjectId);
5995
+ if (effInheritScopes !== undefined) {
5996
+ paramsObj.inherit_scopes = effInheritScopes ? "true" : "false";
5997
+ }
4621
5998
  if (args.include_code !== undefined) paramsObj.include_code = String(Boolean(args.include_code));
4622
5999
  if (args.kind) paramsObj.kind = String(args.kind);
4623
6000
  if (effRedactPolicy) {