@slashml/memory 1.0.16 → 1.1.0
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/README.md +43 -1
- package/bin/cli.js +1149 -18
- package/dist/index.d.ts +92 -0
- package/dist/index.js +342 -4
- package/dist/index.mjs +3 -0
- package/package.json +3 -4
- package/src/index.ts +485 -3
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
|
|
13
|
+
const PACKAGE_VERSION = "1.1.0";
|
|
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)
|
|
@@ -54,7 +65,15 @@ Options:
|
|
|
54
65
|
--file <path> Import memories from a local JSON, JSONL, CSV, or Markdown export file
|
|
55
66
|
import-local, --import-local Import local coding-agent memories (~/.claude/projects/*/memory/*.md, CLAUDE.md, .cursorrules, .windsurfrules, .cursor/rules)
|
|
56
67
|
--dry-run Preview discovered memories during migrate or import-local without writing to / ml
|
|
57
|
-
--
|
|
68
|
+
mint-token, --mint-token Mint a scoped delegated worker/coordinator token (sml_st_*)
|
|
69
|
+
revoke-token, --revoke-token Instantly revoke delegated tokens for --agent <id> or --all
|
|
70
|
+
promote, --promote Promote validated swarm run findings (--run <id>) to durable project memory
|
|
71
|
+
wrap-mcp, --wrap-mcp Wrap any stdio or HTTP MCP server with synchronous / ml PreToolUse & redaction guardrails
|
|
72
|
+
install-shell-guards Install POSIX PATH shims enforcing / ml PreToolUse guardrails on mutating shell CLIs
|
|
73
|
+
guard-exec Execute a shell command behind synchronous / ml PreToolUse policy evaluation
|
|
74
|
+
--run, --run-id <id> Active swarm run identifier (or SLASHML_RUN_ID)
|
|
75
|
+
--project, --project-id <id> Project scope identifier (or SLASHML_PROJECT_ID)
|
|
76
|
+
--json Format status/sync/migrate/token/promote output as JSON
|
|
58
77
|
--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
78
|
--verify <work-email> <code> Verify 6-digit code and print the new SLASHML_API_KEY to stdout`);
|
|
60
79
|
}
|
|
@@ -186,6 +205,9 @@ function parseCliArgs(argv) {
|
|
|
186
205
|
let baseUrl = (process.env.SLASHML_BASE_URL || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
187
206
|
let consoleUrl = (process.env.SLASHML_CONSOLE_URL || DEFAULT_CONSOLE_URL).replace(/\/+$/, "");
|
|
188
207
|
let userId = process.env.SLASHML_USER_ID || "default";
|
|
208
|
+
let explicitUserId = (process.env.SLASHML_USER_ID || "").trim() || null;
|
|
209
|
+
let projectId = (process.env.SLASHML_PROJECT_ID || "").trim() || null;
|
|
210
|
+
let runId = (process.env.SLASHML_RUN_ID || "").trim() || null;
|
|
189
211
|
let agentId = (process.env.SLASHML_AGENT_ID || "").trim() || null;
|
|
190
212
|
let redactPolicy = (process.env.SLASHML_REDACT_POLICY || "").trim() || null;
|
|
191
213
|
let redactScope = (process.env.SLASHML_REDACT_SCOPE || "").trim() || null;
|
|
@@ -217,15 +239,158 @@ function parseCliArgs(argv) {
|
|
|
217
239
|
let importFile = null;
|
|
218
240
|
let isImportLocal = false;
|
|
219
241
|
let isDryRun = false;
|
|
242
|
+
let isMintToken = false;
|
|
243
|
+
let tokenTier = "worker";
|
|
244
|
+
let accessMode = null;
|
|
245
|
+
let ttlSeconds = 3600;
|
|
246
|
+
let canDelegate = false;
|
|
247
|
+
let printEnv = false;
|
|
248
|
+
let isRevokeToken = false;
|
|
249
|
+
let revokeAll = false;
|
|
250
|
+
let isPromote = false;
|
|
251
|
+
let promoteMemoryIds = [];
|
|
252
|
+
let discardUnpromoted = false;
|
|
253
|
+
let isWrapMcp = false;
|
|
254
|
+
let wrapServerName = null;
|
|
255
|
+
let upstreamUrl = null;
|
|
256
|
+
let upstreamCmd = null;
|
|
257
|
+
let wrapArgv = [];
|
|
258
|
+
let isGuardExec = false;
|
|
259
|
+
let guardExecArgv = [];
|
|
260
|
+
let isInstallShellGuards = false;
|
|
261
|
+
let guardBinDir = process.env.SLASHML_GUARD_BIN_DIR || "/tmp/.slashml-guards/bin";
|
|
262
|
+
let guardCommands = null;
|
|
263
|
+
let profilePath = null;
|
|
264
|
+
let guardTimeoutMs = null;
|
|
265
|
+
let failMode = (process.env.SLASHML_GUARD_FAIL_MODE || "open").trim().toLowerCase();
|
|
220
266
|
|
|
221
267
|
for (let i = 0; i < argv.length; i++) {
|
|
222
268
|
const arg = argv[i];
|
|
223
|
-
if (arg === "-
|
|
269
|
+
if (arg === "wrap-mcp" || arg === "--wrap-mcp") {
|
|
270
|
+
isWrapMcp = true;
|
|
271
|
+
for (let j = i + 1; j < argv.length; j++) {
|
|
272
|
+
const w = argv[j];
|
|
273
|
+
if (w === "--") {
|
|
274
|
+
wrapArgv = argv.slice(j + 1);
|
|
275
|
+
break;
|
|
276
|
+
} else if ((w === "--name" || w === "--server-name") && j + 1 < argv.length) {
|
|
277
|
+
wrapServerName = argv[++j].trim() || null;
|
|
278
|
+
} else if ((w === "--upstream-url" || w === "--url") && j + 1 < argv.length) {
|
|
279
|
+
upstreamUrl = argv[++j].trim().replace(/\/+$/, "");
|
|
280
|
+
} else if (w === "--upstream-cmd" && j + 1 < argv.length) {
|
|
281
|
+
upstreamCmd = argv[++j];
|
|
282
|
+
} else if (w === "--api-key" && j + 1 < argv.length) {
|
|
283
|
+
apiKey = argv[++j];
|
|
284
|
+
} else if (w === "--base-url" && j + 1 < argv.length) {
|
|
285
|
+
baseUrl = argv[++j].replace(/\/+$/, "");
|
|
286
|
+
} else if ((w === "--run" || w === "--run-id") && j + 1 < argv.length) {
|
|
287
|
+
runId = argv[++j].trim() || null;
|
|
288
|
+
} else if ((w === "--project" || w === "--project-id") && j + 1 < argv.length) {
|
|
289
|
+
projectId = argv[++j].trim() || null;
|
|
290
|
+
} else if ((w === "--user" || w === "--user-id") && j + 1 < argv.length) {
|
|
291
|
+
userId = argv[++j];
|
|
292
|
+
explicitUserId = userId;
|
|
293
|
+
} else if ((w === "--agent" || w === "--agent-id") && j + 1 < argv.length) {
|
|
294
|
+
agentId = argv[++j].trim() || null;
|
|
295
|
+
} else if (w === "--redact-policy" && j + 1 < argv.length) {
|
|
296
|
+
redactPolicy = argv[++j].trim() || null;
|
|
297
|
+
} else if (w === "--redact-scope" && j + 1 < argv.length) {
|
|
298
|
+
redactScope = argv[++j].trim() || null;
|
|
299
|
+
} else if (w === "--timeout-ms" && j + 1 < argv.length) {
|
|
300
|
+
guardTimeoutMs = Math.max(100, Number(argv[++j]) || 5000);
|
|
301
|
+
} else if (w === "--fail-mode" && j + 1 < argv.length) {
|
|
302
|
+
failMode = argv[++j].trim().toLowerCase();
|
|
303
|
+
} else if (!w.startsWith("-")) {
|
|
304
|
+
wrapArgv = argv.slice(j);
|
|
305
|
+
break;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
break;
|
|
309
|
+
} else if (arg === "guard-exec" || arg === "--guard-exec") {
|
|
310
|
+
isGuardExec = true;
|
|
311
|
+
for (let j = i + 1; j < argv.length; j++) {
|
|
312
|
+
const g = argv[j];
|
|
313
|
+
if (g === "--") {
|
|
314
|
+
guardExecArgv = argv.slice(j + 1);
|
|
315
|
+
break;
|
|
316
|
+
} else if (g === "--api-key" && j + 1 < argv.length) {
|
|
317
|
+
apiKey = argv[++j];
|
|
318
|
+
} else if (g === "--base-url" && j + 1 < argv.length) {
|
|
319
|
+
baseUrl = argv[++j].replace(/\/+$/, "");
|
|
320
|
+
} else if ((g === "--run" || g === "--run-id") && j + 1 < argv.length) {
|
|
321
|
+
runId = argv[++j].trim() || null;
|
|
322
|
+
} else if ((g === "--project" || g === "--project-id") && j + 1 < argv.length) {
|
|
323
|
+
projectId = argv[++j].trim() || null;
|
|
324
|
+
} else if ((g === "--user" || g === "--user-id") && j + 1 < argv.length) {
|
|
325
|
+
userId = argv[++j];
|
|
326
|
+
explicitUserId = userId;
|
|
327
|
+
} else if ((g === "--agent" || g === "--agent-id") && j + 1 < argv.length) {
|
|
328
|
+
agentId = argv[++j].trim() || null;
|
|
329
|
+
} else if (g === "--redact-policy" && j + 1 < argv.length) {
|
|
330
|
+
redactPolicy = argv[++j].trim() || null;
|
|
331
|
+
} else if (g === "--timeout-ms" && j + 1 < argv.length) {
|
|
332
|
+
guardTimeoutMs = Math.max(100, Number(argv[++j]) || 1500);
|
|
333
|
+
} else if (g === "--fail-mode" && j + 1 < argv.length) {
|
|
334
|
+
failMode = argv[++j].trim().toLowerCase();
|
|
335
|
+
} else if (g === "--bin-dir" && j + 1 < argv.length) {
|
|
336
|
+
guardBinDir = argv[++j];
|
|
337
|
+
} else {
|
|
338
|
+
guardExecArgv = argv.slice(j);
|
|
339
|
+
break;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
break;
|
|
343
|
+
} else if (arg === "-h" || arg === "--help" || arg === "help") {
|
|
224
344
|
isHelp = true;
|
|
225
345
|
} else if (arg === "-v" || arg === "--version" || arg === "version") {
|
|
226
346
|
isVersion = true;
|
|
227
347
|
} else if (arg === "init" || arg === "--init") {
|
|
228
348
|
isInit = true;
|
|
349
|
+
} else if (arg === "mint-token" || arg === "--mint-token") {
|
|
350
|
+
isMintToken = true;
|
|
351
|
+
} else if (arg === "revoke-token" || arg === "--revoke-token") {
|
|
352
|
+
isRevokeToken = true;
|
|
353
|
+
} else if (arg === "promote" || arg === "--promote") {
|
|
354
|
+
isPromote = true;
|
|
355
|
+
} else if (arg === "install-shell-guards" || arg === "--install-shell-guards") {
|
|
356
|
+
isInstallShellGuards = true;
|
|
357
|
+
} else if (arg === "--tier" && i + 1 < argv.length) {
|
|
358
|
+
tokenTier = argv[++i].trim().toLowerCase();
|
|
359
|
+
} else if (arg === "--access-mode" && i + 1 < argv.length) {
|
|
360
|
+
accessMode = argv[++i].trim().toLowerCase();
|
|
361
|
+
} else if ((arg === "--ttl" || arg === "--ttl-seconds") && i + 1 < argv.length) {
|
|
362
|
+
ttlSeconds = Math.max(1, Number(argv[++i]) || 3600);
|
|
363
|
+
} else if (arg === "--can-delegate") {
|
|
364
|
+
canDelegate = true;
|
|
365
|
+
} else if (arg === "--env" || arg === "--print-env") {
|
|
366
|
+
printEnv = true;
|
|
367
|
+
} else if (arg === "--all") {
|
|
368
|
+
revokeAll = true;
|
|
369
|
+
} else if (arg === "--memory-ids" && i + 1 < argv.length) {
|
|
370
|
+
const ids = argv[++i]
|
|
371
|
+
.split(",")
|
|
372
|
+
.map((s) => s.trim())
|
|
373
|
+
.filter(Boolean);
|
|
374
|
+
promoteMemoryIds.push(...ids);
|
|
375
|
+
} else if (arg === "--discard-unpromoted") {
|
|
376
|
+
discardUnpromoted = true;
|
|
377
|
+
} else if ((arg === "--run" || arg === "--run-id") && i + 1 < argv.length) {
|
|
378
|
+
runId = argv[++i].trim() || null;
|
|
379
|
+
} else if ((arg === "--project" || arg === "--project-id") && i + 1 < argv.length) {
|
|
380
|
+
projectId = argv[++i].trim() || null;
|
|
381
|
+
} else if (arg === "--bin-dir" && i + 1 < argv.length) {
|
|
382
|
+
guardBinDir = argv[++i];
|
|
383
|
+
} else if (arg === "--commands" && i + 1 < argv.length) {
|
|
384
|
+
guardCommands = argv[++i]
|
|
385
|
+
.split(",")
|
|
386
|
+
.map((s) => s.trim())
|
|
387
|
+
.filter(Boolean);
|
|
388
|
+
} else if (arg === "--profile" && i + 1 < argv.length) {
|
|
389
|
+
profilePath = argv[++i];
|
|
390
|
+
} else if (arg === "--timeout-ms" && i + 1 < argv.length) {
|
|
391
|
+
guardTimeoutMs = Math.max(100, Number(argv[++i]) || 1500);
|
|
392
|
+
} else if (arg === "--fail-mode" && i + 1 < argv.length) {
|
|
393
|
+
failMode = argv[++i].trim().toLowerCase();
|
|
229
394
|
} else if (arg === "--hook" || arg === "hook") {
|
|
230
395
|
isHook = true;
|
|
231
396
|
} else if (arg === "--hook-daemon") {
|
|
@@ -276,9 +441,10 @@ function parseCliArgs(argv) {
|
|
|
276
441
|
baseUrl = argv[++i].replace(/\/+$/, "");
|
|
277
442
|
} else if (arg === "--console-url" && i + 1 < argv.length) {
|
|
278
443
|
consoleUrl = argv[++i].replace(/\/+$/, "");
|
|
279
|
-
} else if (arg === "--user-id" && i + 1 < argv.length) {
|
|
444
|
+
} else if ((arg === "--user" || arg === "--user-id") && i + 1 < argv.length) {
|
|
280
445
|
userId = argv[++i];
|
|
281
|
-
|
|
446
|
+
explicitUserId = userId;
|
|
447
|
+
} else if ((arg === "--agent" || arg === "--agent-id") && i + 1 < argv.length) {
|
|
282
448
|
agentId = argv[++i].trim() || null;
|
|
283
449
|
} else if (arg === "--redact-policy" && i + 1 < argv.length) {
|
|
284
450
|
redactPolicy = argv[++i].trim() || null;
|
|
@@ -317,6 +483,9 @@ function parseCliArgs(argv) {
|
|
|
317
483
|
baseUrl,
|
|
318
484
|
consoleUrl,
|
|
319
485
|
userId,
|
|
486
|
+
explicitUserId,
|
|
487
|
+
projectId,
|
|
488
|
+
runId,
|
|
320
489
|
agentId,
|
|
321
490
|
redactPolicy,
|
|
322
491
|
redactScope,
|
|
@@ -348,6 +517,30 @@ function parseCliArgs(argv) {
|
|
|
348
517
|
importFile,
|
|
349
518
|
isImportLocal,
|
|
350
519
|
isDryRun,
|
|
520
|
+
isMintToken,
|
|
521
|
+
tokenTier,
|
|
522
|
+
accessMode,
|
|
523
|
+
ttlSeconds,
|
|
524
|
+
canDelegate,
|
|
525
|
+
printEnv,
|
|
526
|
+
isRevokeToken,
|
|
527
|
+
revokeAll,
|
|
528
|
+
isPromote,
|
|
529
|
+
promoteMemoryIds,
|
|
530
|
+
discardUnpromoted,
|
|
531
|
+
isWrapMcp,
|
|
532
|
+
wrapServerName,
|
|
533
|
+
upstreamUrl,
|
|
534
|
+
upstreamCmd,
|
|
535
|
+
wrapArgv,
|
|
536
|
+
isGuardExec,
|
|
537
|
+
guardExecArgv,
|
|
538
|
+
isInstallShellGuards,
|
|
539
|
+
guardBinDir,
|
|
540
|
+
guardCommands,
|
|
541
|
+
profilePath,
|
|
542
|
+
guardTimeoutMs,
|
|
543
|
+
failMode,
|
|
351
544
|
};
|
|
352
545
|
}
|
|
353
546
|
|
|
@@ -368,7 +561,12 @@ function saveApiKeyToEnvFile(apiKey, cwd = process.cwd()) {
|
|
|
368
561
|
} else {
|
|
369
562
|
content = content ? `${content.replace(/\n*$/, "")}\n${line}\n` : `${line}\n`;
|
|
370
563
|
}
|
|
371
|
-
fs.writeFileSync(envPath, content, "utf8");
|
|
564
|
+
fs.writeFileSync(envPath, content, { encoding: "utf8", mode: 0o600 });
|
|
565
|
+
try {
|
|
566
|
+
fs.chmodSync(envPath, 0o600);
|
|
567
|
+
} catch {
|
|
568
|
+
// ignore on platforms without POSIX chmod
|
|
569
|
+
}
|
|
372
570
|
|
|
373
571
|
const gitignorePath = path.join(cwd, ".gitignore");
|
|
374
572
|
if (fs.existsSync(gitignorePath)) {
|
|
@@ -452,7 +650,12 @@ function nativeNodeInit(skill, apiKey, repo = null, writeEnv = false, extraEnv =
|
|
|
452
650
|
}
|
|
453
651
|
delete data.mcpServers["/ml-memory"];
|
|
454
652
|
data.mcpServers["ml-memory"] = serverEntry;
|
|
455
|
-
fs.writeFileSync(target, JSON.stringify(data, null, 2) + "\n", "utf8");
|
|
653
|
+
fs.writeFileSync(target, JSON.stringify(data, null, 2) + "\n", { encoding: "utf8", mode: 0o600 });
|
|
654
|
+
try {
|
|
655
|
+
fs.chmodSync(target, 0o600);
|
|
656
|
+
} catch {
|
|
657
|
+
// ignore on platforms without POSIX chmod
|
|
658
|
+
}
|
|
456
659
|
console.log(`Configured ml-memory MCP in ${target}`);
|
|
457
660
|
}
|
|
458
661
|
}
|
|
@@ -2126,6 +2329,7 @@ async function runAmbientHookMode(opts) {
|
|
|
2126
2329
|
model: process.env.SLASHML_MODEL || undefined,
|
|
2127
2330
|
user_id: opts.userId,
|
|
2128
2331
|
...(projectId ? { project_id: projectId } : {}),
|
|
2332
|
+
...(opts.runId ? { run_id: opts.runId } : {}),
|
|
2129
2333
|
session_id: whisperKey,
|
|
2130
2334
|
...(opts.redactPolicy ? { redact_policy: opts.redactPolicy } : {}),
|
|
2131
2335
|
...(opts.redactScope ? { redact_scope: opts.redactScope } : {}),
|
|
@@ -2390,12 +2594,28 @@ async function runAmbientHookMode(opts) {
|
|
|
2390
2594
|
}
|
|
2391
2595
|
}
|
|
2392
2596
|
|
|
2597
|
+
const DEFAULT_SANDBOX_RUN_DIR = path.join(os.homedir(), ".slashml", "run");
|
|
2393
2598
|
const SANDBOX_INTERVENTION_PATH =
|
|
2394
|
-
process.env.SLASHML_SANDBOX_INTERVENTION_PATH ||
|
|
2599
|
+
process.env.SLASHML_SANDBOX_INTERVENTION_PATH ||
|
|
2600
|
+
path.join(DEFAULT_SANDBOX_RUN_DIR, "slashml-sandbox-intervention.json");
|
|
2395
2601
|
const SANDBOX_OFFSETS_PATH =
|
|
2396
|
-
process.env.SLASHML_SANDBOX_OFFSETS_PATH ||
|
|
2602
|
+
process.env.SLASHML_SANDBOX_OFFSETS_PATH ||
|
|
2603
|
+
path.join(DEFAULT_SANDBOX_RUN_DIR, "slashml-sandbox-offsets.json");
|
|
2397
2604
|
const SANDBOX_PID_PATH =
|
|
2398
|
-
process.env.SLASHML_SANDBOX_PID_PATH ||
|
|
2605
|
+
process.env.SLASHML_SANDBOX_PID_PATH ||
|
|
2606
|
+
path.join(DEFAULT_SANDBOX_RUN_DIR, "slashml-watch-sandbox.pid");
|
|
2607
|
+
|
|
2608
|
+
function writePrivateRunFile(targetPath, bodyStr) {
|
|
2609
|
+
const dir = path.dirname(targetPath);
|
|
2610
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
2611
|
+
try {
|
|
2612
|
+
fs.chmodSync(dir, 0o700);
|
|
2613
|
+
} catch {}
|
|
2614
|
+
fs.writeFileSync(targetPath, bodyStr, { encoding: "utf8", mode: 0o600 });
|
|
2615
|
+
try {
|
|
2616
|
+
fs.chmodSync(targetPath, 0o600);
|
|
2617
|
+
} catch {}
|
|
2618
|
+
}
|
|
2399
2619
|
|
|
2400
2620
|
function resolveSandboxTargets(explicitRepo) {
|
|
2401
2621
|
if (explicitRepo && String(explicitRepo).trim()) {
|
|
@@ -2461,7 +2681,10 @@ async function runSyncRulesCommand(opts) {
|
|
|
2461
2681
|
const targets = resolveSandboxTargets(opts.repo);
|
|
2462
2682
|
const primaryDir = targets[0] || process.cwd();
|
|
2463
2683
|
const projectId =
|
|
2464
|
-
|
|
2684
|
+
opts.projectId ||
|
|
2685
|
+
process.env.SLASHML_PROJECT_ID ||
|
|
2686
|
+
path.basename(primaryDir.replace(/[\\/]+$/, "")) ||
|
|
2687
|
+
"default";
|
|
2465
2688
|
|
|
2466
2689
|
if (!opts.apiKey) {
|
|
2467
2690
|
if (!opts.silent) {
|
|
@@ -2488,7 +2711,10 @@ async function runSyncRulesCommand(opts) {
|
|
|
2488
2711
|
user_id: targetUserId,
|
|
2489
2712
|
limit: "200",
|
|
2490
2713
|
include_code: "false",
|
|
2714
|
+
inherit_scopes: "true",
|
|
2491
2715
|
});
|
|
2716
|
+
if (projectId) q.set("project_id", projectId);
|
|
2717
|
+
if (opts.runId) q.set("run_id", opts.runId);
|
|
2492
2718
|
const listResp = await apiRequest(opts, "GET", `/v1/memories?${q.toString()}`);
|
|
2493
2719
|
const rawItems = Array.isArray(listResp)
|
|
2494
2720
|
? listResp
|
|
@@ -2573,6 +2799,8 @@ async function runSyncRulesCommand(opts) {
|
|
|
2573
2799
|
status: "synced",
|
|
2574
2800
|
project_id: projectId,
|
|
2575
2801
|
user_id: opts.userId || "default",
|
|
2802
|
+
...(opts.runId ? { run_id: opts.runId } : {}),
|
|
2803
|
+
vault_revision: lastObservedVaultRevision,
|
|
2576
2804
|
synced_count: memories.length,
|
|
2577
2805
|
memories,
|
|
2578
2806
|
active_intervention: Boolean(activeIntervention),
|
|
@@ -2760,11 +2988,15 @@ async function scanSandboxTranscriptsOnce(opts, state) {
|
|
|
2760
2988
|
const targets = resolveSandboxTargets(opts.repo);
|
|
2761
2989
|
const primaryDir = targets[0] || process.cwd();
|
|
2762
2990
|
const projectId =
|
|
2763
|
-
|
|
2991
|
+
opts.projectId ||
|
|
2992
|
+
process.env.SLASHML_PROJECT_ID ||
|
|
2993
|
+
path.basename(primaryDir.replace(/[\\/]+$/, "")) ||
|
|
2994
|
+
"default";
|
|
2764
2995
|
|
|
2765
2996
|
let processedEvents = 0;
|
|
2766
2997
|
let assimilatedCount = 0;
|
|
2767
2998
|
let intervenedCount = 0;
|
|
2999
|
+
let rulesResynced = false;
|
|
2768
3000
|
const interventions = [];
|
|
2769
3001
|
|
|
2770
3002
|
for (const filePath of files) {
|
|
@@ -2840,6 +3072,7 @@ async function scanSandboxTranscriptsOnce(opts, state) {
|
|
|
2840
3072
|
commit_writes: true,
|
|
2841
3073
|
user_id: opts.userId || "default",
|
|
2842
3074
|
project_id: projectId,
|
|
3075
|
+
...(opts.runId ? { run_id: opts.runId } : {}),
|
|
2843
3076
|
session_id: sessionId,
|
|
2844
3077
|
...(opts.redactPolicy ? { redact_policy: opts.redactPolicy } : {}),
|
|
2845
3078
|
...(opts.redactScope ? { redact_scope: opts.redactScope } : {}),
|
|
@@ -2848,6 +3081,14 @@ async function scanSandboxTranscriptsOnce(opts, state) {
|
|
|
2848
3081
|
processedEvents += 1;
|
|
2849
3082
|
telem.conversation_tokens_processed = (telem.conversation_tokens_processed || 0) + rawTok;
|
|
2850
3083
|
telem.events_processed = (telem.events_processed || 0) + 1;
|
|
3084
|
+
if (
|
|
3085
|
+
lastObservedVaultRevision > Number(state.lastSyncedVaultRevision || 0) &&
|
|
3086
|
+
!(resp && resp.should_write)
|
|
3087
|
+
) {
|
|
3088
|
+
state.lastSyncedVaultRevision = lastObservedVaultRevision;
|
|
3089
|
+
await runSyncRulesCommand({ ...opts, silent: true });
|
|
3090
|
+
rulesResynced = true;
|
|
3091
|
+
}
|
|
2851
3092
|
|
|
2852
3093
|
if (ev.hook_event_name === "UserPromptSubmit" && resp && resp.should_intervene) {
|
|
2853
3094
|
const recalledIds =
|
|
@@ -2876,6 +3117,11 @@ async function scanSandboxTranscriptsOnce(opts, state) {
|
|
|
2876
3117
|
telem.memories_superseded = (telem.memories_superseded || 0) + 1;
|
|
2877
3118
|
}
|
|
2878
3119
|
await runSyncRulesCommand({ ...opts, silent: true });
|
|
3120
|
+
state.lastSyncedVaultRevision = Math.max(
|
|
3121
|
+
Number(state.lastSyncedVaultRevision || 0),
|
|
3122
|
+
lastObservedVaultRevision
|
|
3123
|
+
);
|
|
3124
|
+
rulesResynced = true;
|
|
2879
3125
|
}
|
|
2880
3126
|
if (isMidTurnBlock) {
|
|
2881
3127
|
intervenedCount += 1;
|
|
@@ -2894,10 +3140,9 @@ async function scanSandboxTranscriptsOnce(opts, state) {
|
|
|
2894
3140
|
activeIntervention: resp.intervention_message,
|
|
2895
3141
|
});
|
|
2896
3142
|
try {
|
|
2897
|
-
|
|
3143
|
+
writePrivateRunFile(
|
|
2898
3144
|
SANDBOX_INTERVENTION_PATH,
|
|
2899
|
-
JSON.stringify(interventionRecord, null, 2) + "\n"
|
|
2900
|
-
"utf8"
|
|
3145
|
+
JSON.stringify(interventionRecord, null, 2) + "\n"
|
|
2901
3146
|
);
|
|
2902
3147
|
} catch {
|
|
2903
3148
|
// ignore
|
|
@@ -2909,7 +3154,20 @@ async function scanSandboxTranscriptsOnce(opts, state) {
|
|
|
2909
3154
|
const ellipsisBase = (
|
|
2910
3155
|
process.env.ELLIPSIS_API_URL || "https://api.ellipsis.dev"
|
|
2911
3156
|
).replace(/\/+$/, "");
|
|
2912
|
-
|
|
3157
|
+
state.notifiedRulesBySession = state.notifiedRulesBySession || {};
|
|
3158
|
+
const notifiedRuleSet = new Set(
|
|
3159
|
+
Array.isArray(state.notifiedRulesBySession[sessionId])
|
|
3160
|
+
? state.notifiedRulesBySession[sessionId]
|
|
3161
|
+
: []
|
|
3162
|
+
);
|
|
3163
|
+
const ruleFingerprints =
|
|
3164
|
+
Array.isArray(resp.violated_memory_ids) && resp.violated_memory_ids.length > 0
|
|
3165
|
+
? resp.violated_memory_ids.map(String)
|
|
3166
|
+
: [String(resp.intervention_message).slice(0, 120)];
|
|
3167
|
+
const hasNovelRule = ruleFingerprints.some((fp) => !notifiedRuleSet.has(fp));
|
|
3168
|
+
if (ellipsisSessionId && ellipsisToken && hasNovelRule) {
|
|
3169
|
+
for (const fp of ruleFingerprints) notifiedRuleSet.add(fp);
|
|
3170
|
+
state.notifiedRulesBySession[sessionId] = Array.from(notifiedRuleSet).slice(-64);
|
|
2913
3171
|
state.notifiedSessions[sessionId] = true;
|
|
2914
3172
|
try {
|
|
2915
3173
|
await fetch(`${ellipsisBase}/v1/sessions/${ellipsisSessionId}/messages`, {
|
|
@@ -2939,8 +3197,21 @@ async function scanSandboxTranscriptsOnce(opts, state) {
|
|
|
2939
3197
|
}
|
|
2940
3198
|
}
|
|
2941
3199
|
|
|
3200
|
+
if (processedEvents === 0 && opts.apiKey) {
|
|
3201
|
+
try {
|
|
3202
|
+
await apiRequest(opts, "GET", "/v1/memory/status");
|
|
3203
|
+
if (lastObservedVaultRevision > Number(state.lastSyncedVaultRevision || 0)) {
|
|
3204
|
+
state.lastSyncedVaultRevision = lastObservedVaultRevision;
|
|
3205
|
+
await runSyncRulesCommand({ ...opts, silent: true });
|
|
3206
|
+
rulesResynced = true;
|
|
3207
|
+
}
|
|
3208
|
+
} catch {
|
|
3209
|
+
// fail-open when status probe is unreachable
|
|
3210
|
+
}
|
|
3211
|
+
}
|
|
3212
|
+
|
|
2942
3213
|
try {
|
|
2943
|
-
|
|
3214
|
+
writePrivateRunFile(SANDBOX_OFFSETS_PATH, JSON.stringify(state, null, 2) + "\n");
|
|
2944
3215
|
} catch {
|
|
2945
3216
|
// ignore offset persistence error
|
|
2946
3217
|
}
|
|
@@ -2950,6 +3221,8 @@ async function scanSandboxTranscriptsOnce(opts, state) {
|
|
|
2950
3221
|
processed_events: processedEvents,
|
|
2951
3222
|
memories_assimilated: assimilatedCount,
|
|
2952
3223
|
interventions_triggered: intervenedCount,
|
|
3224
|
+
rules_resynced: rulesResynced,
|
|
3225
|
+
vault_revision: lastObservedVaultRevision,
|
|
2953
3226
|
interventions,
|
|
2954
3227
|
};
|
|
2955
3228
|
}
|
|
@@ -2967,7 +3240,7 @@ async function runWatchSandboxCommand(opts) {
|
|
|
2967
3240
|
});
|
|
2968
3241
|
child.unref();
|
|
2969
3242
|
try {
|
|
2970
|
-
|
|
3243
|
+
writePrivateRunFile(SANDBOX_PID_PATH, String(child.pid) + "\n");
|
|
2971
3244
|
} catch {
|
|
2972
3245
|
// ignore
|
|
2973
3246
|
}
|
|
@@ -2986,6 +3259,8 @@ async function runWatchSandboxCommand(opts) {
|
|
|
2986
3259
|
lastPromptBySession: {},
|
|
2987
3260
|
whisperedBySession: {},
|
|
2988
3261
|
notifiedSessions: {},
|
|
3262
|
+
notifiedRulesBySession: {},
|
|
3263
|
+
lastSyncedVaultRevision: 0,
|
|
2989
3264
|
};
|
|
2990
3265
|
if (fs.existsSync(SANDBOX_OFFSETS_PATH)) {
|
|
2991
3266
|
try {
|
|
@@ -2996,6 +3271,8 @@ async function runWatchSandboxCommand(opts) {
|
|
|
2996
3271
|
lastPromptBySession: loaded.lastPromptBySession || {},
|
|
2997
3272
|
whisperedBySession: loaded.whisperedBySession || {},
|
|
2998
3273
|
notifiedSessions: loaded.notifiedSessions || {},
|
|
3274
|
+
notifiedRulesBySession: loaded.notifiedRulesBySession || {},
|
|
3275
|
+
lastSyncedVaultRevision: Number(loaded.lastSyncedVaultRevision || 0),
|
|
2999
3276
|
};
|
|
3000
3277
|
}
|
|
3001
3278
|
} catch {
|
|
@@ -3704,6 +3981,839 @@ async function runImportLocalCommand(opts) {
|
|
|
3704
3981
|
}
|
|
3705
3982
|
}
|
|
3706
3983
|
|
|
3984
|
+
const DEFAULT_GUARDED_SHELL_COMMANDS = [
|
|
3985
|
+
"psql",
|
|
3986
|
+
"mysql",
|
|
3987
|
+
"sqlite3",
|
|
3988
|
+
"redis-cli",
|
|
3989
|
+
"mongosh",
|
|
3990
|
+
"git",
|
|
3991
|
+
"gh",
|
|
3992
|
+
"rm",
|
|
3993
|
+
"mv",
|
|
3994
|
+
"kubectl",
|
|
3995
|
+
"helm",
|
|
3996
|
+
"terraform",
|
|
3997
|
+
"pulumi",
|
|
3998
|
+
"wrangler",
|
|
3999
|
+
"aws",
|
|
4000
|
+
"gcloud",
|
|
4001
|
+
"az",
|
|
4002
|
+
"stripe",
|
|
4003
|
+
"docker",
|
|
4004
|
+
"npm",
|
|
4005
|
+
"pnpm",
|
|
4006
|
+
"yarn",
|
|
4007
|
+
"pip",
|
|
4008
|
+
"uv",
|
|
4009
|
+
"curl",
|
|
4010
|
+
"wget",
|
|
4011
|
+
];
|
|
4012
|
+
|
|
4013
|
+
function shellQuoteArg(val) {
|
|
4014
|
+
const s = String(val ?? "");
|
|
4015
|
+
if (!s) return "''";
|
|
4016
|
+
if (/^[a-zA-Z0-9_./:@=+-]+$/.test(s)) return s;
|
|
4017
|
+
return `'${s.replace(/'/g, "'\\''")}'`;
|
|
4018
|
+
}
|
|
4019
|
+
|
|
4020
|
+
async function runMintTokenCommand(opts) {
|
|
4021
|
+
const targetAgent = String(opts.agentId || "").trim();
|
|
4022
|
+
if (!targetAgent) {
|
|
4023
|
+
throw new Error("mint-token requires --agent <agent_id> (or SLASHML_AGENT_ID).");
|
|
4024
|
+
}
|
|
4025
|
+
const payload = {
|
|
4026
|
+
authority_tier: opts.tokenTier || "worker",
|
|
4027
|
+
ttl_seconds: Number(opts.ttlSeconds || 3600),
|
|
4028
|
+
can_delegate: Boolean(opts.canDelegate),
|
|
4029
|
+
};
|
|
4030
|
+
if (opts.runId) payload.run_id = opts.runId;
|
|
4031
|
+
if (opts.projectId) payload.project_id = opts.projectId;
|
|
4032
|
+
if (opts.explicitUserId) payload.user_id = opts.explicitUserId;
|
|
4033
|
+
if (opts.accessMode) payload.access_mode = opts.accessMode;
|
|
4034
|
+
if (opts.redactPolicy) {
|
|
4035
|
+
payload.redact_policy = opts.redactPolicy.includes(",")
|
|
4036
|
+
? opts.redactPolicy
|
|
4037
|
+
.split(",")
|
|
4038
|
+
.map((s) => s.trim())
|
|
4039
|
+
.filter(Boolean)
|
|
4040
|
+
: opts.redactPolicy;
|
|
4041
|
+
}
|
|
4042
|
+
if (opts.redactScope) payload.redact_scope = opts.redactScope;
|
|
4043
|
+
|
|
4044
|
+
const mintOpts = { ...opts, agentId: null };
|
|
4045
|
+
const res = await apiRequest(
|
|
4046
|
+
mintOpts,
|
|
4047
|
+
"POST",
|
|
4048
|
+
`/v1/agents/${encodeURIComponent(targetAgent)}/tokens`,
|
|
4049
|
+
payload
|
|
4050
|
+
);
|
|
4051
|
+
|
|
4052
|
+
if (opts.printEnv) {
|
|
4053
|
+
const lines = [
|
|
4054
|
+
`export SLASHML_API_KEY=${shellQuoteArg(res.token)}`,
|
|
4055
|
+
`export SLASHML_AGENT_ID=${shellQuoteArg(targetAgent)}`,
|
|
4056
|
+
];
|
|
4057
|
+
const resolvedRunId =
|
|
4058
|
+
res.run_id || (res.claims && (res.claims.rid || res.claims.run)) || opts.runId;
|
|
4059
|
+
if (resolvedRunId) {
|
|
4060
|
+
lines.push(`export SLASHML_RUN_ID=${shellQuoteArg(resolvedRunId)}`);
|
|
4061
|
+
}
|
|
4062
|
+
const resolvedProjectId =
|
|
4063
|
+
res.project_id || (res.claims && res.claims.prj) || opts.projectId;
|
|
4064
|
+
if (resolvedProjectId) {
|
|
4065
|
+
lines.push(`export SLASHML_PROJECT_ID=${shellQuoteArg(resolvedProjectId)}`);
|
|
4066
|
+
}
|
|
4067
|
+
process.stdout.write(lines.join("\n") + "\n");
|
|
4068
|
+
return res;
|
|
4069
|
+
}
|
|
4070
|
+
if (opts.jsonOutput) {
|
|
4071
|
+
process.stdout.write(JSON.stringify(res, null, 2) + "\n");
|
|
4072
|
+
} else {
|
|
4073
|
+
process.stdout.write(`${res.token}\n`);
|
|
4074
|
+
}
|
|
4075
|
+
return res;
|
|
4076
|
+
}
|
|
4077
|
+
|
|
4078
|
+
async function runRevokeTokenCommand(opts) {
|
|
4079
|
+
const revokeOpts = { ...opts, agentId: null };
|
|
4080
|
+
let res;
|
|
4081
|
+
if (opts.revokeAll) {
|
|
4082
|
+
res = await apiRequest(revokeOpts, "POST", "/v1/agents/revoke-all", {});
|
|
4083
|
+
} else {
|
|
4084
|
+
const targetAgent = String(opts.agentId || "").trim();
|
|
4085
|
+
if (!targetAgent) {
|
|
4086
|
+
throw new Error("revoke-token requires --agent <agent_id> or --all.");
|
|
4087
|
+
}
|
|
4088
|
+
res = await apiRequest(
|
|
4089
|
+
revokeOpts,
|
|
4090
|
+
"POST",
|
|
4091
|
+
`/v1/agents/${encodeURIComponent(targetAgent)}/revoke`,
|
|
4092
|
+
{}
|
|
4093
|
+
);
|
|
4094
|
+
}
|
|
4095
|
+
if (opts.jsonOutput) {
|
|
4096
|
+
process.stdout.write(JSON.stringify(res, null, 2) + "\n");
|
|
4097
|
+
} else if (opts.revokeAll) {
|
|
4098
|
+
console.log("[/ ml] Revoked all delegated swarm tokens in workspace.");
|
|
4099
|
+
} else {
|
|
4100
|
+
console.log(`[/ ml] Revoked delegated swarm tokens for agent '${res.agent_id}'.`);
|
|
4101
|
+
}
|
|
4102
|
+
return res;
|
|
4103
|
+
}
|
|
4104
|
+
|
|
4105
|
+
async function runPromoteCommand(opts) {
|
|
4106
|
+
if (!opts.runId) {
|
|
4107
|
+
throw new Error("promote requires --run <run_id> (or SLASHML_RUN_ID).");
|
|
4108
|
+
}
|
|
4109
|
+
const payload = {
|
|
4110
|
+
run_id: opts.runId,
|
|
4111
|
+
discard_unpromoted: Boolean(opts.discardUnpromoted),
|
|
4112
|
+
};
|
|
4113
|
+
if (opts.projectId) payload.target_project_id = opts.projectId;
|
|
4114
|
+
if (opts.explicitUserId) payload.target_user_id = opts.explicitUserId;
|
|
4115
|
+
if (Array.isArray(opts.promoteMemoryIds) && opts.promoteMemoryIds.length > 0) {
|
|
4116
|
+
payload.memory_ids = opts.promoteMemoryIds;
|
|
4117
|
+
}
|
|
4118
|
+
const res = await apiRequest(opts, "POST", "/v1/memory/promote", payload);
|
|
4119
|
+
if (opts.jsonOutput) {
|
|
4120
|
+
process.stdout.write(JSON.stringify(res, null, 2) + "\n");
|
|
4121
|
+
} else {
|
|
4122
|
+
console.log(
|
|
4123
|
+
`[/ ml] Promoted ${res.promoted_count || 0} memory record(s) from run '${opts.runId}' (discarded=${res.discarded_count || 0}).`
|
|
4124
|
+
);
|
|
4125
|
+
}
|
|
4126
|
+
return res;
|
|
4127
|
+
}
|
|
4128
|
+
|
|
4129
|
+
function runInstallShellGuardsCommand(opts) {
|
|
4130
|
+
const binDir = path.resolve(opts.guardBinDir || "/tmp/.slashml-guards/bin");
|
|
4131
|
+
fs.mkdirSync(binDir, { recursive: true, mode: 0o755 });
|
|
4132
|
+
const rawCommands =
|
|
4133
|
+
Array.isArray(opts.guardCommands) && opts.guardCommands.length > 0
|
|
4134
|
+
? opts.guardCommands
|
|
4135
|
+
: DEFAULT_GUARDED_SHELL_COMMANDS;
|
|
4136
|
+
const installed = [];
|
|
4137
|
+
const nodeBin = process.execPath;
|
|
4138
|
+
const selfScript = path.resolve(__filename);
|
|
4139
|
+
|
|
4140
|
+
for (const rawCmd of rawCommands) {
|
|
4141
|
+
const cmd = String(rawCmd || "").trim();
|
|
4142
|
+
if (!cmd || !/^[a-zA-Z0-9._+-]+$/.test(cmd)) continue;
|
|
4143
|
+
const shimPath = path.join(binDir, cmd);
|
|
4144
|
+
const shimBody = [
|
|
4145
|
+
"#!/bin/sh",
|
|
4146
|
+
`SLASHML_GUARD_SELF_DIR=${shellQuoteArg(binDir)} exec ${shellQuoteArg(nodeBin)} ${shellQuoteArg(selfScript)} guard-exec -- ${shellQuoteArg(cmd)} "$@"`,
|
|
4147
|
+
"",
|
|
4148
|
+
].join("\n");
|
|
4149
|
+
fs.writeFileSync(shimPath, shimBody, { encoding: "utf8", mode: 0o755 });
|
|
4150
|
+
try {
|
|
4151
|
+
fs.chmodSync(shimPath, 0o755);
|
|
4152
|
+
} catch {}
|
|
4153
|
+
installed.push(cmd);
|
|
4154
|
+
}
|
|
4155
|
+
|
|
4156
|
+
const exportLine = `export PATH=${shellQuoteArg(binDir)}:"$PATH"`;
|
|
4157
|
+
if (opts.profilePath) {
|
|
4158
|
+
const prof = path.resolve(opts.profilePath);
|
|
4159
|
+
let existing = "";
|
|
4160
|
+
if (fs.existsSync(prof)) {
|
|
4161
|
+
try {
|
|
4162
|
+
existing = fs.readFileSync(prof, "utf8");
|
|
4163
|
+
} catch {}
|
|
4164
|
+
}
|
|
4165
|
+
if (!existing.includes(binDir)) {
|
|
4166
|
+
const next = existing ? `${existing.replace(/\n*$/, "")}\n${exportLine}\n` : `${exportLine}\n`;
|
|
4167
|
+
fs.mkdirSync(path.dirname(prof), { recursive: true });
|
|
4168
|
+
fs.writeFileSync(prof, next, "utf8");
|
|
4169
|
+
}
|
|
4170
|
+
}
|
|
4171
|
+
|
|
4172
|
+
const payload = {
|
|
4173
|
+
status: "installed",
|
|
4174
|
+
bin_dir: binDir,
|
|
4175
|
+
commands: installed,
|
|
4176
|
+
installed_count: installed.length,
|
|
4177
|
+
path_export: exportLine,
|
|
4178
|
+
};
|
|
4179
|
+
if (opts.printEnv) {
|
|
4180
|
+
process.stdout.write(`${exportLine}\n`);
|
|
4181
|
+
} else if (opts.jsonOutput) {
|
|
4182
|
+
process.stdout.write(JSON.stringify(payload, null, 2) + "\n");
|
|
4183
|
+
} else {
|
|
4184
|
+
console.log(
|
|
4185
|
+
`[/ ml] Installed ${installed.length} shell guardrail shims in ${binDir}.\nActivate in your shell or Dockerfile:\n ${exportLine}`
|
|
4186
|
+
);
|
|
4187
|
+
}
|
|
4188
|
+
return payload;
|
|
4189
|
+
}
|
|
4190
|
+
|
|
4191
|
+
function isReadOnlyGuardExecCommand(cmdName, cmdArgs) {
|
|
4192
|
+
const base = path.basename(String(cmdName || "")).toLowerCase();
|
|
4193
|
+
const args = Array.isArray(cmdArgs) ? cmdArgs.map((a) => String(a)) : [];
|
|
4194
|
+
if (
|
|
4195
|
+
args.length === 1 &&
|
|
4196
|
+
(args[0] === "--version" || args[0] === "-v" || args[0] === "--help" || args[0] === "-h")
|
|
4197
|
+
) {
|
|
4198
|
+
return true;
|
|
4199
|
+
}
|
|
4200
|
+
if (base === "git") {
|
|
4201
|
+
let idx = 0;
|
|
4202
|
+
while (idx < args.length) {
|
|
4203
|
+
const tok = args[idx];
|
|
4204
|
+
if (tok === "-C" || tok === "-c" || tok === "--git-dir" || tok === "--work-tree") {
|
|
4205
|
+
idx += 2;
|
|
4206
|
+
continue;
|
|
4207
|
+
}
|
|
4208
|
+
if (tok.startsWith("-")) {
|
|
4209
|
+
idx += 1;
|
|
4210
|
+
continue;
|
|
4211
|
+
}
|
|
4212
|
+
break;
|
|
4213
|
+
}
|
|
4214
|
+
const sub = (args[idx] || "").toLowerCase();
|
|
4215
|
+
const rest = args.slice(idx + 1);
|
|
4216
|
+
if (
|
|
4217
|
+
sub === "status" ||
|
|
4218
|
+
sub === "diff" ||
|
|
4219
|
+
sub === "log" ||
|
|
4220
|
+
sub === "show" ||
|
|
4221
|
+
sub === "rev-parse" ||
|
|
4222
|
+
sub === "ls-files" ||
|
|
4223
|
+
sub === "describe" ||
|
|
4224
|
+
sub === "blame"
|
|
4225
|
+
) {
|
|
4226
|
+
return true;
|
|
4227
|
+
}
|
|
4228
|
+
if (sub === "branch") {
|
|
4229
|
+
return !rest.some((r) => /^-(d|D|m|M|c|C)$|^--delete$|^--move$/.test(r));
|
|
4230
|
+
}
|
|
4231
|
+
if (sub === "remote") {
|
|
4232
|
+
return rest.length === 0 || (rest.length === 1 && rest[0] === "-v") || rest[0] === "get-url";
|
|
4233
|
+
}
|
|
4234
|
+
return false;
|
|
4235
|
+
}
|
|
4236
|
+
if (base === "kubectl") {
|
|
4237
|
+
const firstNonFlag = args.find((a) => !a.startsWith("-")) || "";
|
|
4238
|
+
return ["get", "describe", "logs", "version", "api-resources", "explain"].includes(
|
|
4239
|
+
firstNonFlag.toLowerCase()
|
|
4240
|
+
);
|
|
4241
|
+
}
|
|
4242
|
+
if (base === "aws") {
|
|
4243
|
+
const positional = args.filter((a) => !a.startsWith("-"));
|
|
4244
|
+
return positional[0] === "sts" && positional[1] === "get-caller-identity";
|
|
4245
|
+
}
|
|
4246
|
+
if (base === "docker") {
|
|
4247
|
+
const firstNonFlag = (args.find((a) => !a.startsWith("-")) || "").toLowerCase();
|
|
4248
|
+
return ["ps", "images", "inspect", "logs", "version", "info"].includes(firstNonFlag);
|
|
4249
|
+
}
|
|
4250
|
+
return false;
|
|
4251
|
+
}
|
|
4252
|
+
|
|
4253
|
+
function resolveRealBinaryPath(cmdName, excludedDirs) {
|
|
4254
|
+
const excluded = new Set(
|
|
4255
|
+
(excludedDirs || [])
|
|
4256
|
+
.filter(Boolean)
|
|
4257
|
+
.map((d) => {
|
|
4258
|
+
try {
|
|
4259
|
+
return fs.realpathSync(path.resolve(d));
|
|
4260
|
+
} catch {
|
|
4261
|
+
return path.resolve(d);
|
|
4262
|
+
}
|
|
4263
|
+
})
|
|
4264
|
+
);
|
|
4265
|
+
if (cmdName.includes("/") || cmdName.includes(path.sep)) {
|
|
4266
|
+
const resolved = path.resolve(cmdName);
|
|
4267
|
+
const dir = path.dirname(resolved);
|
|
4268
|
+
let realDir = dir;
|
|
4269
|
+
try {
|
|
4270
|
+
realDir = fs.realpathSync(dir);
|
|
4271
|
+
} catch {}
|
|
4272
|
+
if (!excluded.has(dir) && !excluded.has(realDir) && fs.existsSync(resolved)) {
|
|
4273
|
+
return resolved;
|
|
4274
|
+
}
|
|
4275
|
+
return null;
|
|
4276
|
+
}
|
|
4277
|
+
const pathEnv = process.env.PATH || "";
|
|
4278
|
+
const segments = pathEnv.split(path.delimiter).filter(Boolean);
|
|
4279
|
+
for (const seg of segments) {
|
|
4280
|
+
const absSeg = path.resolve(seg);
|
|
4281
|
+
let realSeg = absSeg;
|
|
4282
|
+
try {
|
|
4283
|
+
realSeg = fs.realpathSync(absSeg);
|
|
4284
|
+
} catch {}
|
|
4285
|
+
if (excluded.has(absSeg) || excluded.has(realSeg)) continue;
|
|
4286
|
+
const candidate = path.join(absSeg, cmdName);
|
|
4287
|
+
try {
|
|
4288
|
+
const st = fs.statSync(candidate);
|
|
4289
|
+
if (st.isFile()) {
|
|
4290
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
4291
|
+
return candidate;
|
|
4292
|
+
}
|
|
4293
|
+
} catch {
|
|
4294
|
+
continue;
|
|
4295
|
+
}
|
|
4296
|
+
}
|
|
4297
|
+
return null;
|
|
4298
|
+
}
|
|
4299
|
+
|
|
4300
|
+
function formatGuardBlockBanner(rawMessage) {
|
|
4301
|
+
const msg = String(rawMessage || "Action blocked by SlashML workspace guardrail.").trim();
|
|
4302
|
+
if (msg.includes("[SLASHML GUARDRAIL BLOCK]")) return msg;
|
|
4303
|
+
return `[SLASHML GUARDRAIL BLOCK] ${msg}`;
|
|
4304
|
+
}
|
|
4305
|
+
|
|
4306
|
+
async function evaluateGuardrailPreToolUse(opts, toolName, toolInput, summaryText, timeoutMs) {
|
|
4307
|
+
if (!opts.apiKey) {
|
|
4308
|
+
if (opts.failMode === "closed") {
|
|
4309
|
+
return {
|
|
4310
|
+
blocked: true,
|
|
4311
|
+
message: "[SLASHML GUARDRAIL BLOCK] SLASHML_API_KEY missing in fail-closed guardrail mode.",
|
|
4312
|
+
};
|
|
4313
|
+
}
|
|
4314
|
+
return { blocked: false };
|
|
4315
|
+
}
|
|
4316
|
+
const controller = new AbortController();
|
|
4317
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
4318
|
+
try {
|
|
4319
|
+
const headers = {
|
|
4320
|
+
Authorization: `Bearer ${opts.apiKey}`,
|
|
4321
|
+
"Content-Type": "application/json",
|
|
4322
|
+
"User-Agent": `slashml-guard/${PACKAGE_VERSION}`,
|
|
4323
|
+
};
|
|
4324
|
+
if (opts.agentId) headers["X-SlashML-Agent-Id"] = opts.agentId;
|
|
4325
|
+
if (opts.runId) headers["X-SlashML-Run-Id"] = opts.runId;
|
|
4326
|
+
if (opts.projectId) headers["X-SlashML-Project-Id"] = opts.projectId;
|
|
4327
|
+
const body = {
|
|
4328
|
+
hook_event_name: "PreToolUse",
|
|
4329
|
+
strict_pretool_block: true,
|
|
4330
|
+
prompt: summaryText,
|
|
4331
|
+
text: summaryText,
|
|
4332
|
+
tool_name: toolName,
|
|
4333
|
+
tool_input: toolInput,
|
|
4334
|
+
commit_writes: false,
|
|
4335
|
+
user_id: opts.userId || "default",
|
|
4336
|
+
...(opts.projectId ? { project_id: opts.projectId } : {}),
|
|
4337
|
+
...(opts.runId ? { run_id: opts.runId } : {}),
|
|
4338
|
+
...(opts.agentId ? { caller_agent_id: opts.agentId } : {}),
|
|
4339
|
+
...(opts.redactPolicy ? { redact_policy: opts.redactPolicy } : {}),
|
|
4340
|
+
...(opts.redactScope ? { redact_scope: opts.redactScope } : {}),
|
|
4341
|
+
};
|
|
4342
|
+
const res = await fetch(`${opts.baseUrl}/v1/memory/intervene`, {
|
|
4343
|
+
method: "POST",
|
|
4344
|
+
headers,
|
|
4345
|
+
body: JSON.stringify(body),
|
|
4346
|
+
signal: controller.signal,
|
|
4347
|
+
});
|
|
4348
|
+
updateObservedVaultRevisionFromResponse(res);
|
|
4349
|
+
const raw = await res.text();
|
|
4350
|
+
let data = {};
|
|
4351
|
+
try {
|
|
4352
|
+
data = raw ? JSON.parse(raw) : {};
|
|
4353
|
+
} catch {
|
|
4354
|
+
data = {};
|
|
4355
|
+
}
|
|
4356
|
+
if (res.status === 401 || res.status === 403) {
|
|
4357
|
+
const detail = data.detail || data.error || `HTTP ${res.status}`;
|
|
4358
|
+
return {
|
|
4359
|
+
blocked: true,
|
|
4360
|
+
message: formatGuardBlockBanner(`Agent credential rejected: ${detail}`),
|
|
4361
|
+
};
|
|
4362
|
+
}
|
|
4363
|
+
if (!res.ok) {
|
|
4364
|
+
if (opts.failMode === "closed") {
|
|
4365
|
+
return {
|
|
4366
|
+
blocked: true,
|
|
4367
|
+
message: formatGuardBlockBanner(`Guardrail service returned HTTP ${res.status}.`),
|
|
4368
|
+
};
|
|
4369
|
+
}
|
|
4370
|
+
return { blocked: false };
|
|
4371
|
+
}
|
|
4372
|
+
const hookEnv = data && typeof data.hook_output === "object" ? data.hook_output : data;
|
|
4373
|
+
const hookOut =
|
|
4374
|
+
hookEnv && typeof hookEnv.hookSpecificOutput === "object"
|
|
4375
|
+
? hookEnv.hookSpecificOutput
|
|
4376
|
+
: data && typeof data.hookSpecificOutput === "object"
|
|
4377
|
+
? data.hookSpecificOutput
|
|
4378
|
+
: null;
|
|
4379
|
+
const permDec = hookOut ? String(hookOut.permissionDecision || "").toLowerCase() : "";
|
|
4380
|
+
const isBlocked =
|
|
4381
|
+
data &&
|
|
4382
|
+
(data.intervention_severity === "BLOCK" ||
|
|
4383
|
+
data.action === "BLOCK" ||
|
|
4384
|
+
data.decision === "BLOCK" ||
|
|
4385
|
+
permDec === "deny");
|
|
4386
|
+
if (isBlocked) {
|
|
4387
|
+
const msgText =
|
|
4388
|
+
data.intervention_message ||
|
|
4389
|
+
(hookOut && hookOut.permissionDecisionReason) ||
|
|
4390
|
+
data.whisper ||
|
|
4391
|
+
"";
|
|
4392
|
+
return {
|
|
4393
|
+
blocked: true,
|
|
4394
|
+
message: formatGuardBlockBanner(msgText),
|
|
4395
|
+
violated_memory_ids: data.violated_memory_ids || data.whispered_memory_ids || [],
|
|
4396
|
+
};
|
|
4397
|
+
}
|
|
4398
|
+
return { blocked: false, response: data };
|
|
4399
|
+
} catch (err) {
|
|
4400
|
+
if (opts.failMode === "closed") {
|
|
4401
|
+
return {
|
|
4402
|
+
blocked: true,
|
|
4403
|
+
message: formatGuardBlockBanner(
|
|
4404
|
+
`Guardrail check unreachable in fail-closed mode: ${err.message || err}`
|
|
4405
|
+
),
|
|
4406
|
+
};
|
|
4407
|
+
}
|
|
4408
|
+
return { blocked: false };
|
|
4409
|
+
} finally {
|
|
4410
|
+
clearTimeout(timer);
|
|
4411
|
+
}
|
|
4412
|
+
}
|
|
4413
|
+
|
|
4414
|
+
async function redactTextViaGuardrail(opts, text, timeoutMs = 4000) {
|
|
4415
|
+
if (!opts.apiKey || !text || !String(text).trim()) return text;
|
|
4416
|
+
const shouldRun =
|
|
4417
|
+
(opts.redactPolicy && opts.redactPolicy !== "off") ||
|
|
4418
|
+
String(opts.apiKey).startsWith("sml_st_");
|
|
4419
|
+
if (!shouldRun) return text;
|
|
4420
|
+
const controller = new AbortController();
|
|
4421
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
4422
|
+
try {
|
|
4423
|
+
const headers = {
|
|
4424
|
+
Authorization: `Bearer ${opts.apiKey}`,
|
|
4425
|
+
"Content-Type": "application/json",
|
|
4426
|
+
"User-Agent": `slashml-guard/${PACKAGE_VERSION}`,
|
|
4427
|
+
};
|
|
4428
|
+
if (opts.agentId) headers["X-SlashML-Agent-Id"] = opts.agentId;
|
|
4429
|
+
if (opts.runId) headers["X-SlashML-Run-Id"] = opts.runId;
|
|
4430
|
+
if (opts.projectId) headers["X-SlashML-Project-Id"] = opts.projectId;
|
|
4431
|
+
const payload = {
|
|
4432
|
+
text: String(text),
|
|
4433
|
+
...(opts.redactPolicy ? { redact_policy: opts.redactPolicy } : {}),
|
|
4434
|
+
};
|
|
4435
|
+
const res = await fetch(`${opts.baseUrl}/v1/memory/redact`, {
|
|
4436
|
+
method: "POST",
|
|
4437
|
+
headers,
|
|
4438
|
+
body: JSON.stringify(payload),
|
|
4439
|
+
signal: controller.signal,
|
|
4440
|
+
});
|
|
4441
|
+
updateObservedVaultRevisionFromResponse(res);
|
|
4442
|
+
if (!res.ok) return text;
|
|
4443
|
+
const data = await res.json();
|
|
4444
|
+
if (data && typeof data.redacted_text === "string") {
|
|
4445
|
+
return data.redacted_text;
|
|
4446
|
+
}
|
|
4447
|
+
return text;
|
|
4448
|
+
} catch {
|
|
4449
|
+
return text;
|
|
4450
|
+
} finally {
|
|
4451
|
+
clearTimeout(timer);
|
|
4452
|
+
}
|
|
4453
|
+
}
|
|
4454
|
+
|
|
4455
|
+
async function runGuardExecCommand(opts) {
|
|
4456
|
+
const argv = Array.isArray(opts.guardExecArgv) ? opts.guardExecArgv : [];
|
|
4457
|
+
if (argv.length === 0) {
|
|
4458
|
+
process.stderr.write("Usage: slashml-memory guard-exec [options] -- <command> [args...]\n");
|
|
4459
|
+
return 2;
|
|
4460
|
+
}
|
|
4461
|
+
const [cmdName, ...cmdArgs] = argv;
|
|
4462
|
+
const excludedDirs = [
|
|
4463
|
+
process.env.SLASHML_GUARD_SELF_DIR,
|
|
4464
|
+
opts.guardBinDir,
|
|
4465
|
+
process.env.SLASHML_GUARD_BIN_DIR,
|
|
4466
|
+
"/tmp/.slashml-guards/bin",
|
|
4467
|
+
];
|
|
4468
|
+
|
|
4469
|
+
if (!isReadOnlyGuardExecCommand(cmdName, cmdArgs)) {
|
|
4470
|
+
const fullCmd = [cmdName, ...cmdArgs].map(shellQuoteArg).join(" ");
|
|
4471
|
+
const timeoutMs =
|
|
4472
|
+
opts.guardTimeoutMs || Math.max(100, Number(process.env.SLASHML_GUARD_TIMEOUT_MS || 1500));
|
|
4473
|
+
const check = await evaluateGuardrailPreToolUse(
|
|
4474
|
+
opts,
|
|
4475
|
+
"Bash",
|
|
4476
|
+
{ command: fullCmd, binary: cmdName, argv: cmdArgs },
|
|
4477
|
+
fullCmd,
|
|
4478
|
+
timeoutMs
|
|
4479
|
+
);
|
|
4480
|
+
if (check.blocked) {
|
|
4481
|
+
process.stderr.write(`${check.message}\n`);
|
|
4482
|
+
return 126;
|
|
4483
|
+
}
|
|
4484
|
+
}
|
|
4485
|
+
|
|
4486
|
+
const realBin = resolveRealBinaryPath(cmdName, excludedDirs);
|
|
4487
|
+
if (!realBin) {
|
|
4488
|
+
process.stderr.write(`${cmdName}: command not found\n`);
|
|
4489
|
+
return 127;
|
|
4490
|
+
}
|
|
4491
|
+
const { spawnSync } = require("child_process");
|
|
4492
|
+
const cleanPath = (process.env.PATH || "")
|
|
4493
|
+
.split(path.delimiter)
|
|
4494
|
+
.filter((seg) => {
|
|
4495
|
+
if (!seg) return false;
|
|
4496
|
+
const abs = path.resolve(seg);
|
|
4497
|
+
return abs !== path.resolve(process.env.SLASHML_GUARD_SELF_DIR || "\0");
|
|
4498
|
+
})
|
|
4499
|
+
.join(path.delimiter);
|
|
4500
|
+
const childRes = spawnSync(realBin, cmdArgs, {
|
|
4501
|
+
stdio: "inherit",
|
|
4502
|
+
env: { ...process.env, PATH: cleanPath },
|
|
4503
|
+
});
|
|
4504
|
+
if (childRes.error) {
|
|
4505
|
+
process.stderr.write(`${cmdName}: ${childRes.error.message}\n`);
|
|
4506
|
+
return 127;
|
|
4507
|
+
}
|
|
4508
|
+
if (typeof childRes.status === "number") {
|
|
4509
|
+
return childRes.status;
|
|
4510
|
+
}
|
|
4511
|
+
return 1;
|
|
4512
|
+
}
|
|
4513
|
+
|
|
4514
|
+
async function scrubMcpResponseContent(opts, respMsg, timeoutMs) {
|
|
4515
|
+
if (
|
|
4516
|
+
!respMsg ||
|
|
4517
|
+
typeof respMsg !== "object" ||
|
|
4518
|
+
!respMsg.result ||
|
|
4519
|
+
!Array.isArray(respMsg.result.content)
|
|
4520
|
+
) {
|
|
4521
|
+
return respMsg;
|
|
4522
|
+
}
|
|
4523
|
+
for (const block of respMsg.result.content) {
|
|
4524
|
+
if (block && block.type === "text" && typeof block.text === "string" && block.text.trim()) {
|
|
4525
|
+
block.text = await redactTextViaGuardrail(opts, block.text, timeoutMs);
|
|
4526
|
+
}
|
|
4527
|
+
}
|
|
4528
|
+
return respMsg;
|
|
4529
|
+
}
|
|
4530
|
+
|
|
4531
|
+
async function runWrapMcpCommand(opts) {
|
|
4532
|
+
const timeoutMs =
|
|
4533
|
+
opts.guardTimeoutMs || Math.max(250, Number(process.env.SLASHML_GUARD_TIMEOUT_MS || 5000));
|
|
4534
|
+
|
|
4535
|
+
if (opts.upstreamUrl) {
|
|
4536
|
+
const clientRl = readline.createInterface({ input: process.stdin, terminal: false });
|
|
4537
|
+
let chain = Promise.resolve();
|
|
4538
|
+
let upstreamSessionId = null;
|
|
4539
|
+
clientRl.on("line", (rawLine) => {
|
|
4540
|
+
const trimmed = rawLine.trim();
|
|
4541
|
+
if (!trimmed) return;
|
|
4542
|
+
chain = chain.then(async () => {
|
|
4543
|
+
let msg;
|
|
4544
|
+
try {
|
|
4545
|
+
msg = JSON.parse(trimmed);
|
|
4546
|
+
} catch {
|
|
4547
|
+
return;
|
|
4548
|
+
}
|
|
4549
|
+
if (msg && msg.method === "tools/call") {
|
|
4550
|
+
const toolName = String((msg.params && msg.params.name) || "");
|
|
4551
|
+
const toolArgs = (msg.params && msg.params.arguments) || {};
|
|
4552
|
+
const summary = `${toolName} ${JSON.stringify(toolArgs)}`;
|
|
4553
|
+
const check = await evaluateGuardrailPreToolUse(
|
|
4554
|
+
opts,
|
|
4555
|
+
toolName,
|
|
4556
|
+
toolArgs,
|
|
4557
|
+
summary,
|
|
4558
|
+
timeoutMs
|
|
4559
|
+
);
|
|
4560
|
+
if (check.blocked) {
|
|
4561
|
+
process.stdout.write(
|
|
4562
|
+
JSON.stringify({
|
|
4563
|
+
jsonrpc: "2.0",
|
|
4564
|
+
id: msg.id,
|
|
4565
|
+
result: {
|
|
4566
|
+
isError: true,
|
|
4567
|
+
content: [{ type: "text", text: check.message }],
|
|
4568
|
+
},
|
|
4569
|
+
}) + "\n"
|
|
4570
|
+
);
|
|
4571
|
+
return;
|
|
4572
|
+
}
|
|
4573
|
+
}
|
|
4574
|
+
try {
|
|
4575
|
+
const headers = {
|
|
4576
|
+
"Content-Type": "application/json",
|
|
4577
|
+
Accept: "application/json",
|
|
4578
|
+
};
|
|
4579
|
+
if (upstreamSessionId) headers["Mcp-Session-Id"] = upstreamSessionId;
|
|
4580
|
+
const upRes = await fetch(opts.upstreamUrl, {
|
|
4581
|
+
method: "POST",
|
|
4582
|
+
headers,
|
|
4583
|
+
body: JSON.stringify(msg),
|
|
4584
|
+
});
|
|
4585
|
+
const sid = upRes.headers.get("mcp-session-id");
|
|
4586
|
+
if (sid) upstreamSessionId = sid;
|
|
4587
|
+
if (upRes.status === 202 || msg.id === undefined || msg.id === null) {
|
|
4588
|
+
return;
|
|
4589
|
+
}
|
|
4590
|
+
let respMsg = await upRes.json();
|
|
4591
|
+
if (msg && msg.method === "tools/call") {
|
|
4592
|
+
respMsg = await scrubMcpResponseContent(opts, respMsg, timeoutMs);
|
|
4593
|
+
}
|
|
4594
|
+
process.stdout.write(JSON.stringify(respMsg) + "\n");
|
|
4595
|
+
} catch (err) {
|
|
4596
|
+
if (msg && msg.id !== undefined && msg.id !== null) {
|
|
4597
|
+
process.stdout.write(
|
|
4598
|
+
JSON.stringify({
|
|
4599
|
+
jsonrpc: "2.0",
|
|
4600
|
+
id: msg.id,
|
|
4601
|
+
error: { code: -32603, message: `Upstream MCP error: ${err.message || err}` },
|
|
4602
|
+
}) + "\n"
|
|
4603
|
+
);
|
|
4604
|
+
}
|
|
4605
|
+
}
|
|
4606
|
+
});
|
|
4607
|
+
});
|
|
4608
|
+
await new Promise((resolve) => {
|
|
4609
|
+
clientRl.on("close", () => {
|
|
4610
|
+
chain.then(resolve).catch(resolve);
|
|
4611
|
+
});
|
|
4612
|
+
});
|
|
4613
|
+
return;
|
|
4614
|
+
}
|
|
4615
|
+
|
|
4616
|
+
let cmdBin = null;
|
|
4617
|
+
let cmdArgs = [];
|
|
4618
|
+
let useShell = false;
|
|
4619
|
+
if (Array.isArray(opts.wrapArgv) && opts.wrapArgv.length > 0) {
|
|
4620
|
+
[cmdBin, ...cmdArgs] = opts.wrapArgv;
|
|
4621
|
+
} else if (opts.upstreamCmd && String(opts.upstreamCmd).trim()) {
|
|
4622
|
+
cmdBin = String(opts.upstreamCmd).trim();
|
|
4623
|
+
useShell = true;
|
|
4624
|
+
} else {
|
|
4625
|
+
throw new Error(
|
|
4626
|
+
"wrap-mcp requires an upstream command (`slashml-memory wrap-mcp -- <cmd> [args...]`) or `--upstream-url <url>`."
|
|
4627
|
+
);
|
|
4628
|
+
}
|
|
4629
|
+
|
|
4630
|
+
const { spawn } = require("child_process");
|
|
4631
|
+
const child = spawn(cmdBin, cmdArgs, {
|
|
4632
|
+
stdio: ["pipe", "pipe", "inherit"],
|
|
4633
|
+
env: process.env,
|
|
4634
|
+
shell: useShell,
|
|
4635
|
+
});
|
|
4636
|
+
|
|
4637
|
+
const pendingToolCalls = new Map();
|
|
4638
|
+
let inFlightRequests = 0;
|
|
4639
|
+
let stdinClosed = false;
|
|
4640
|
+
let childExited = false;
|
|
4641
|
+
|
|
4642
|
+
function maybeCloseChildStdin() {
|
|
4643
|
+
if (stdinClosed && inFlightRequests <= 0 && !childExited) {
|
|
4644
|
+
try {
|
|
4645
|
+
child.stdin.end();
|
|
4646
|
+
} catch {}
|
|
4647
|
+
}
|
|
4648
|
+
}
|
|
4649
|
+
|
|
4650
|
+
const childRl = readline.createInterface({ input: child.stdout, terminal: false });
|
|
4651
|
+
let outChain = Promise.resolve();
|
|
4652
|
+
childRl.on("line", (rawLine) => {
|
|
4653
|
+
const trimmed = rawLine.trim();
|
|
4654
|
+
if (!trimmed) return;
|
|
4655
|
+
outChain = outChain.then(async () => {
|
|
4656
|
+
let respMsg;
|
|
4657
|
+
try {
|
|
4658
|
+
respMsg = JSON.parse(trimmed);
|
|
4659
|
+
} catch {
|
|
4660
|
+
process.stdout.write(rawLine + "\n");
|
|
4661
|
+
return;
|
|
4662
|
+
}
|
|
4663
|
+
const hasId = respMsg && respMsg.id !== undefined && respMsg.id !== null;
|
|
4664
|
+
if (hasId) {
|
|
4665
|
+
const idKey = String(respMsg.id);
|
|
4666
|
+
if (pendingToolCalls.has(idKey)) {
|
|
4667
|
+
pendingToolCalls.delete(idKey);
|
|
4668
|
+
respMsg = await scrubMcpResponseContent(opts, respMsg, timeoutMs);
|
|
4669
|
+
}
|
|
4670
|
+
inFlightRequests = Math.max(0, inFlightRequests - 1);
|
|
4671
|
+
}
|
|
4672
|
+
process.stdout.write(JSON.stringify(respMsg) + "\n");
|
|
4673
|
+
if (hasId) {
|
|
4674
|
+
maybeCloseChildStdin();
|
|
4675
|
+
}
|
|
4676
|
+
});
|
|
4677
|
+
});
|
|
4678
|
+
|
|
4679
|
+
const clientRl = readline.createInterface({ input: process.stdin, terminal: false });
|
|
4680
|
+
let inChain = Promise.resolve();
|
|
4681
|
+
clientRl.on("line", (rawLine) => {
|
|
4682
|
+
const trimmed = rawLine.trim();
|
|
4683
|
+
if (!trimmed) return;
|
|
4684
|
+
inChain = inChain.then(async () => {
|
|
4685
|
+
let msg;
|
|
4686
|
+
try {
|
|
4687
|
+
msg = JSON.parse(trimmed);
|
|
4688
|
+
} catch {
|
|
4689
|
+
if (!childExited) {
|
|
4690
|
+
child.stdin.write(rawLine + "\n");
|
|
4691
|
+
}
|
|
4692
|
+
return;
|
|
4693
|
+
}
|
|
4694
|
+
if (msg && msg.method === "tools/call") {
|
|
4695
|
+
const toolName = String((msg.params && msg.params.name) || "");
|
|
4696
|
+
const toolArgs = (msg.params && msg.params.arguments) || {};
|
|
4697
|
+
const summary = `${toolName} ${JSON.stringify(toolArgs)}`;
|
|
4698
|
+
const check = await evaluateGuardrailPreToolUse(
|
|
4699
|
+
opts,
|
|
4700
|
+
toolName,
|
|
4701
|
+
toolArgs,
|
|
4702
|
+
summary,
|
|
4703
|
+
timeoutMs
|
|
4704
|
+
);
|
|
4705
|
+
if (check.blocked) {
|
|
4706
|
+
if (msg.id !== undefined && msg.id !== null) {
|
|
4707
|
+
process.stdout.write(
|
|
4708
|
+
JSON.stringify({
|
|
4709
|
+
jsonrpc: "2.0",
|
|
4710
|
+
id: msg.id,
|
|
4711
|
+
result: {
|
|
4712
|
+
isError: true,
|
|
4713
|
+
content: [{ type: "text", text: check.message }],
|
|
4714
|
+
},
|
|
4715
|
+
}) + "\n"
|
|
4716
|
+
);
|
|
4717
|
+
}
|
|
4718
|
+
maybeCloseChildStdin();
|
|
4719
|
+
return;
|
|
4720
|
+
}
|
|
4721
|
+
if (msg.id !== undefined && msg.id !== null) {
|
|
4722
|
+
pendingToolCalls.set(String(msg.id), { toolName });
|
|
4723
|
+
}
|
|
4724
|
+
}
|
|
4725
|
+
if (msg && msg.id !== undefined && msg.id !== null) {
|
|
4726
|
+
inFlightRequests += 1;
|
|
4727
|
+
}
|
|
4728
|
+
if (!childExited) {
|
|
4729
|
+
child.stdin.write(JSON.stringify(msg) + "\n");
|
|
4730
|
+
}
|
|
4731
|
+
});
|
|
4732
|
+
});
|
|
4733
|
+
|
|
4734
|
+
clientRl.on("close", () => {
|
|
4735
|
+
inChain
|
|
4736
|
+
.then(() => {
|
|
4737
|
+
stdinClosed = true;
|
|
4738
|
+
maybeCloseChildStdin();
|
|
4739
|
+
})
|
|
4740
|
+
.catch(() => {
|
|
4741
|
+
stdinClosed = true;
|
|
4742
|
+
maybeCloseChildStdin();
|
|
4743
|
+
});
|
|
4744
|
+
});
|
|
4745
|
+
|
|
4746
|
+
const exitCode = await new Promise((resolve, reject) => {
|
|
4747
|
+
child.on("error", reject);
|
|
4748
|
+
child.on("close", (code) => {
|
|
4749
|
+
childExited = true;
|
|
4750
|
+
outChain.then(() => resolve(code || 0)).catch(() => resolve(code || 0));
|
|
4751
|
+
});
|
|
4752
|
+
});
|
|
4753
|
+
process.exitCode = exitCode;
|
|
4754
|
+
}
|
|
4755
|
+
|
|
4756
|
+
if (parsed.isMintToken) {
|
|
4757
|
+
runMintTokenCommand(parsed)
|
|
4758
|
+
.then(() => process.exit(0))
|
|
4759
|
+
.catch((err) => {
|
|
4760
|
+
console.error(`Error: ${err.message || err}`);
|
|
4761
|
+
process.exit(1);
|
|
4762
|
+
});
|
|
4763
|
+
return;
|
|
4764
|
+
}
|
|
4765
|
+
|
|
4766
|
+
if (parsed.isRevokeToken) {
|
|
4767
|
+
runRevokeTokenCommand(parsed)
|
|
4768
|
+
.then(() => process.exit(0))
|
|
4769
|
+
.catch((err) => {
|
|
4770
|
+
console.error(`Error: ${err.message || err}`);
|
|
4771
|
+
process.exit(1);
|
|
4772
|
+
});
|
|
4773
|
+
return;
|
|
4774
|
+
}
|
|
4775
|
+
|
|
4776
|
+
if (parsed.isPromote) {
|
|
4777
|
+
runPromoteCommand(parsed)
|
|
4778
|
+
.then(() => process.exit(0))
|
|
4779
|
+
.catch((err) => {
|
|
4780
|
+
console.error(`Error: ${err.message || err}`);
|
|
4781
|
+
process.exit(1);
|
|
4782
|
+
});
|
|
4783
|
+
return;
|
|
4784
|
+
}
|
|
4785
|
+
|
|
4786
|
+
if (parsed.isInstallShellGuards) {
|
|
4787
|
+
try {
|
|
4788
|
+
runInstallShellGuardsCommand(parsed);
|
|
4789
|
+
process.exit(0);
|
|
4790
|
+
} catch (err) {
|
|
4791
|
+
console.error(`Error: ${err.message || err}`);
|
|
4792
|
+
process.exit(1);
|
|
4793
|
+
}
|
|
4794
|
+
return;
|
|
4795
|
+
}
|
|
4796
|
+
|
|
4797
|
+
if (parsed.isGuardExec) {
|
|
4798
|
+
runGuardExecCommand(parsed)
|
|
4799
|
+
.then((code) => process.exit(typeof code === "number" ? code : 0))
|
|
4800
|
+
.catch((err) => {
|
|
4801
|
+
console.error(`Error: ${err.message || err}`);
|
|
4802
|
+
process.exit(1);
|
|
4803
|
+
});
|
|
4804
|
+
return;
|
|
4805
|
+
}
|
|
4806
|
+
|
|
4807
|
+
if (parsed.isWrapMcp) {
|
|
4808
|
+
runWrapMcpCommand(parsed)
|
|
4809
|
+
.then(() => process.exit(process.exitCode || 0))
|
|
4810
|
+
.catch((err) => {
|
|
4811
|
+
console.error(`Error: ${err.message || err}`);
|
|
4812
|
+
process.exit(1);
|
|
4813
|
+
});
|
|
4814
|
+
return;
|
|
4815
|
+
}
|
|
4816
|
+
|
|
3707
4817
|
if (parsed.isMigrate) {
|
|
3708
4818
|
runMigrateCommand(parsed)
|
|
3709
4819
|
.then(() => process.exit(0))
|
|
@@ -4395,11 +5505,18 @@ async function apiRequest(opts, method, urlPath, body) {
|
|
|
4395
5505
|
if (opts.agentId) {
|
|
4396
5506
|
headers["X-SlashML-Agent-Id"] = opts.agentId;
|
|
4397
5507
|
}
|
|
5508
|
+
if (opts.runId) {
|
|
5509
|
+
headers["X-SlashML-Run-Id"] = opts.runId;
|
|
5510
|
+
}
|
|
5511
|
+
if (opts.projectId) {
|
|
5512
|
+
headers["X-SlashML-Project-Id"] = opts.projectId;
|
|
5513
|
+
}
|
|
4398
5514
|
const res = await fetch(`${opts.baseUrl}${urlPath}`, {
|
|
4399
5515
|
method,
|
|
4400
5516
|
headers,
|
|
4401
5517
|
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
4402
5518
|
});
|
|
5519
|
+
updateObservedVaultRevisionFromResponse(res);
|
|
4403
5520
|
const text = await res.text();
|
|
4404
5521
|
const data = text ? JSON.parse(text) : {};
|
|
4405
5522
|
if (!res.ok) {
|
|
@@ -4564,11 +5681,20 @@ async function dispatchTool(opts, name, args = {}) {
|
|
|
4564
5681
|
const effRedactPolicy = args.redact_policy !== undefined ? args.redact_policy : opts.redactPolicy;
|
|
4565
5682
|
const effRedactScope = args.redact_scope !== undefined ? args.redact_scope : opts.redactScope;
|
|
4566
5683
|
const effAgentId = args.caller_agent_id || opts.agentId || null;
|
|
5684
|
+
const effRunId = args.run_id || opts.runId || null;
|
|
5685
|
+
const effProjectId = args.project_id || opts.projectId || null;
|
|
5686
|
+
const effInheritScopes =
|
|
5687
|
+
typeof args.inherit_scopes === "boolean" ? args.inherit_scopes : undefined;
|
|
4567
5688
|
|
|
4568
5689
|
function withLifecycle(payload) {
|
|
4569
5690
|
if (effRedactPolicy) payload.redact_policy = effRedactPolicy;
|
|
4570
5691
|
if (effRedactScope) payload.redact_scope = effRedactScope;
|
|
4571
5692
|
if (effAgentId) payload.caller_agent_id = effAgentId;
|
|
5693
|
+
if (effRunId && payload.run_id === undefined) payload.run_id = effRunId;
|
|
5694
|
+
if (effProjectId && payload.project_id === undefined) payload.project_id = effProjectId;
|
|
5695
|
+
if (effInheritScopes !== undefined && payload.inherit_scopes === undefined) {
|
|
5696
|
+
payload.inherit_scopes = effInheritScopes;
|
|
5697
|
+
}
|
|
4572
5698
|
return payload;
|
|
4573
5699
|
}
|
|
4574
5700
|
|
|
@@ -4618,6 +5744,11 @@ async function dispatchTool(opts, name, args = {}) {
|
|
|
4618
5744
|
}
|
|
4619
5745
|
if (name === "get_memories") {
|
|
4620
5746
|
const paramsObj = { user_id: uid, limit: String(args.limit || 50) };
|
|
5747
|
+
if (effRunId) paramsObj.run_id = String(effRunId);
|
|
5748
|
+
if (effProjectId) paramsObj.project_id = String(effProjectId);
|
|
5749
|
+
if (effInheritScopes !== undefined) {
|
|
5750
|
+
paramsObj.inherit_scopes = effInheritScopes ? "true" : "false";
|
|
5751
|
+
}
|
|
4621
5752
|
if (args.include_code !== undefined) paramsObj.include_code = String(Boolean(args.include_code));
|
|
4622
5753
|
if (args.kind) paramsObj.kind = String(args.kind);
|
|
4623
5754
|
if (effRedactPolicy) {
|