@kontextmind/kxm 0.7.6 → 0.7.8

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.
@@ -2986,7 +2986,7 @@ var require_compile = __commonJS({
2986
2986
  const schOrFunc = root.refs[ref];
2987
2987
  if (schOrFunc)
2988
2988
  return schOrFunc;
2989
- let _sch = resolve8.call(this, root, ref);
2989
+ let _sch = resolve9.call(this, root, ref);
2990
2990
  if (_sch === void 0) {
2991
2991
  const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref];
2992
2992
  const { schemaId } = this.opts;
@@ -3013,7 +3013,7 @@ var require_compile = __commonJS({
3013
3013
  function sameSchemaEnv(s1, s2) {
3014
3014
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
3015
3015
  }
3016
- function resolve8(root, ref) {
3016
+ function resolve9(root, ref) {
3017
3017
  let sch;
3018
3018
  while (typeof (sch = this.refs[ref]) == "string")
3019
3019
  ref = sch;
@@ -3838,7 +3838,7 @@ var require_fast_uri = __commonJS({
3838
3838
  }
3839
3839
  return uri;
3840
3840
  }
3841
- function resolve8(baseURI, relativeURI, options) {
3841
+ function resolve9(baseURI, relativeURI, options) {
3842
3842
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
3843
3843
  const {
3844
3844
  parsed: baseParsed,
@@ -4200,7 +4200,7 @@ var require_fast_uri = __commonJS({
4200
4200
  var fastUri = {
4201
4201
  SCHEMES,
4202
4202
  normalize,
4203
- resolve: resolve8,
4203
+ resolve: resolve9,
4204
4204
  resolveComponent,
4205
4205
  equal,
4206
4206
  serialize,
@@ -15139,7 +15139,7 @@ function defaultSpawn(command, args, options) {
15139
15139
  if (options.signal?.aborted) {
15140
15140
  return Promise.resolve({ stdout: "", stderr: "", code: null, started: false, observedChildExit: false, error: new Error("process_aborted") });
15141
15141
  }
15142
- return new Promise((resolve8) => {
15142
+ return new Promise((resolve9) => {
15143
15143
  const stdout = [];
15144
15144
  const stderr = [];
15145
15145
  let outputBytes = 0;
@@ -15168,7 +15168,7 @@ function defaultSpawn(command, args, options) {
15168
15168
  child?.unref();
15169
15169
  const started = Boolean(child?.pid);
15170
15170
  if (started && !observedChildExit) error ??= new Error("process_exit_unobserved");
15171
- resolve8({ stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8"), code, signal, started, observedChildExit, terminationRequested: stopping, ...error ? { error } : {} });
15171
+ resolve9({ stdout: Buffer.concat(stdout).toString("utf8"), stderr: Buffer.concat(stderr).toString("utf8"), code, signal, started, observedChildExit, terminationRequested: stopping, ...error ? { error } : {} });
15172
15172
  };
15173
15173
  const kill = (requested) => {
15174
15174
  killProcessTree(child, requested);
@@ -16925,8 +16925,8 @@ function validateWorkflow(workflow, agents, models, repositories, gates, issues)
16925
16925
  const writable = Object.values(objectValue(step.repositories) ?? {}).filter((access) => access === "write").length;
16926
16926
  if (maxWriteRepositories > writable) issues.push(issue2("semantic", "write_repository_bound_invalid", file, `${stepId} maxWriteRepositories exceeds writable repository scope`));
16927
16927
  }
16928
- const join16 = objectValue(step.join);
16929
- const minimumPassed = join16 && typeof join16.minimumPassed === "number" ? join16.minimumPassed : void 0;
16928
+ const join17 = objectValue(step.join);
16929
+ const minimumPassed = join17 && typeof join17.minimumPassed === "number" ? join17.minimumPassed : void 0;
16930
16930
  if (minimumPassed !== void 0 && minimumPassed > maximum) issues.push(issue2("semantic", "join_impossible", file, `${stepId} minimumPassed exceeds assignment maximum`));
16931
16931
  const distinctBy = names(assignment?.distinctBy);
16932
16932
  if (distinctBy.length > 0) {
@@ -20454,7 +20454,7 @@ function compileStep(step, index, stepIndex, requirePlanHash, sink) {
20454
20454
  const maxAttempts = compileCountField(step.maxAttempts, 1, `${id}.maxAttempts`, id, sink);
20455
20455
  const timeoutMs = compileOptionalDuration(step.timeoutMs, `${id}.timeoutMs`, id, sink);
20456
20456
  const assignments = compileAssignments(step, id, agent, sink);
20457
- const join16 = compileJoin(step, id, sink);
20457
+ const join17 = compileJoin(step, id, sink);
20458
20458
  const requiredEvidence = compileEvidence(step, id, sink);
20459
20459
  const transitions = compileTransitions(step, id, index, stepIndex, sink);
20460
20460
  const outcomes = Object.keys(transitions).sort(compareCodeUnits4);
@@ -20482,7 +20482,7 @@ function compileStep(step, index, stepIndex, requirePlanHash, sink) {
20482
20482
  transitions: orderedTransitions,
20483
20483
  requiresPlanHash: requirePlanHash.includes(id),
20484
20484
  assignments,
20485
- join: join16
20485
+ join: join17
20486
20486
  };
20487
20487
  if (kind === "agent" || kind === "moa") {
20488
20488
  if (!agent) return void 0;
@@ -20532,15 +20532,15 @@ function compileAssignments(step, stepId, primaryAgentId, sink) {
20532
20532
  };
20533
20533
  }
20534
20534
  function compileJoin(step, stepId, sink) {
20535
- const join16 = objectValue2(step.join);
20536
- if (!join16) return { strategy: "all" };
20537
- const declared = stringValue2(join16.strategy);
20535
+ const join17 = objectValue2(step.join);
20536
+ if (!join17) return { strategy: "all" };
20537
+ const declared = stringValue2(join17.strategy);
20538
20538
  const strategy = declared && JOIN_STRATEGIES.has(declared) ? declared : "all";
20539
- const minimumPassed = compileOptionalCount(join16.minimumPassed, `${stepId}.join.minimumPassed`, stepId, sink);
20539
+ const minimumPassed = compileOptionalCount(join17.minimumPassed, `${stepId}.join.minimumPassed`, stepId, sink);
20540
20540
  const compiled = {
20541
20541
  strategy,
20542
20542
  ...minimumPassed !== void 0 ? { minimumPassed } : {},
20543
- ...typeof join16.cancelRemaining === "boolean" ? { cancelRemaining: join16.cancelRemaining } : {}
20543
+ ...typeof join17.cancelRemaining === "boolean" ? { cancelRemaining: join17.cancelRemaining } : {}
20544
20544
  };
20545
20545
  return compiled;
20546
20546
  }
@@ -21835,12 +21835,12 @@ function enqueueVnextScheduledRun(storePath, runId, configRevision, bound, start
21835
21835
  if (owner.admitted.has(runId) || owner.queue.some((item) => item.runId === runId)) {
21836
21836
  return Promise.reject(runtimeError("run_busy", runId, `run ${runId} is already admitted or queued`));
21837
21837
  }
21838
- return new Promise((resolve8, reject) => {
21838
+ return new Promise((resolve9, reject) => {
21839
21839
  owner.queue.push({
21840
21840
  runId,
21841
21841
  configRevision,
21842
21842
  bound,
21843
- start: (token) => start(token).then(resolve8, reject),
21843
+ start: (token) => start(token).then(resolve9, reject),
21844
21844
  fail: (error) => reject(error)
21845
21845
  });
21846
21846
  pump(storePath, owner);
@@ -23013,6 +23013,17 @@ var INSECURE_SSH_HOST_KEY_PATTERNS = Object.freeze([
23013
23013
  /StrictHostKeyChecking=(accept-new|no|off)/i,
23014
23014
  /UserKnownHostsFile=\/dev\/null/i
23015
23015
  ]);
23016
+ function assertPinnedSshHostKeyPolicy(sshArgs) {
23017
+ for (const arg of sshArgs) {
23018
+ for (const pattern of INSECURE_SSH_HOST_KEY_PATTERNS) {
23019
+ if (pattern.test(arg)) {
23020
+ throw new Error(
23021
+ `Insecure SSH host key policy rejected: "${arg}". KXM headless SSH requires pinned host keys with StrictHostKeyChecking=yes and BatchMode=yes.`
23022
+ );
23023
+ }
23024
+ }
23025
+ }
23026
+ }
23016
23027
 
23017
23028
  // plugins/kxm/src/vnext-engine-command.ts
23018
23029
  var MAX_DIRECT_TIMER_MS = 2147483647;
@@ -23100,8 +23111,8 @@ var CommandObserver = class {
23100
23111
  this.requestStop("error", "lost-close");
23101
23112
  }
23102
23113
  run() {
23103
- return new Promise((resolve8) => {
23104
- this.resolveOutcome = resolve8;
23114
+ return new Promise((resolve9) => {
23115
+ this.resolveOutcome = resolve9;
23105
23116
  try {
23106
23117
  this.start();
23107
23118
  } catch (error) {
@@ -26532,8 +26543,8 @@ async function startVnextRuntimeSupervisorInner(paths, requestedPortOption, now)
26532
26543
  }
26533
26544
  let releaseActive = () => {
26534
26545
  };
26535
- const activePromise = new Promise((resolve8) => {
26536
- releaseActive = resolve8;
26546
+ const activePromise = new Promise((resolve9) => {
26547
+ releaseActive = resolve9;
26537
26548
  });
26538
26549
  activeDrives.set(runId, activePromise);
26539
26550
  const cleanupActive = () => {
@@ -26989,8 +27000,8 @@ var PiSession = class {
26989
27000
  }
26990
27001
  const id = `cmd_${++this.commandCounter}`;
26991
27002
  const payload = { ...command, id };
26992
- return new Promise((resolve8, reject) => {
26993
- this.pendingCommands.set(id, { resolve: resolve8, reject });
27003
+ return new Promise((resolve9, reject) => {
27004
+ this.pendingCommands.set(id, { resolve: resolve9, reject });
26994
27005
  try {
26995
27006
  this.process.stdin.write(JSON.stringify(payload) + "\n");
26996
27007
  } catch (err) {
@@ -27011,7 +27022,7 @@ var PiSession = class {
27011
27022
  return { outcome, text: "aborted", usage: {} };
27012
27023
  }
27013
27024
  this.status = "busy";
27014
- return new Promise((resolve8, reject) => {
27025
+ return new Promise((resolve9, reject) => {
27015
27026
  let signalCleanup;
27016
27027
  if (signal) {
27017
27028
  const onAbort = () => {
@@ -27025,7 +27036,7 @@ var PiSession = class {
27025
27036
  signalCleanup = () => signal.removeEventListener("abort", onAbort);
27026
27037
  }
27027
27038
  this.activePrompt = {
27028
- resolve: resolve8,
27039
+ resolve: resolve9,
27029
27040
  reject,
27030
27041
  allowedOutcomes,
27031
27042
  text: "",
@@ -28418,23 +28429,622 @@ ${divider}
28418
28429
  `;
28419
28430
  return out;
28420
28431
  }
28432
+
28433
+ // plugins/kxm/src/ssh-remote.ts
28434
+ import { spawnSync as spawnSync3 } from "node:child_process";
28435
+ import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync11, readdirSync as readdirSync5, rmSync as rmSync2, statSync as statSync4 } from "node:fs";
28436
+ import { homedir as homedir2 } from "node:os";
28437
+ import { join as join16, resolve as resolve8 } from "node:path";
28438
+ var MAX_SSH_OUTPUT_BYTES = 50 * 1024;
28439
+ var MAX_SSH_OUTPUT_LINES = 2e3;
28440
+ var DEFAULT_SOCKET_DIR = ".kxm/run/ssh-sockets";
28441
+ var DEFAULT_CONTROL_PERSIST = "10m";
28442
+ function truncateSshOutput(raw) {
28443
+ let text = raw;
28444
+ let truncated = false;
28445
+ if (Buffer.byteLength(text, "utf-8") > MAX_SSH_OUTPUT_BYTES) {
28446
+ const buf = Buffer.from(text, "utf-8");
28447
+ text = buf.subarray(0, MAX_SSH_OUTPUT_BYTES).toString("utf-8");
28448
+ truncated = true;
28449
+ }
28450
+ const lines = text.split("\n");
28451
+ if (lines.length > MAX_SSH_OUTPUT_LINES) {
28452
+ text = lines.slice(0, MAX_SSH_OUTPUT_LINES).join("\n");
28453
+ truncated = true;
28454
+ }
28455
+ if (truncated) {
28456
+ text += `
28457
+
28458
+ [kxm: ssh output truncated to ${MAX_SSH_OUTPUT_BYTES / 1024}KB / ${MAX_SSH_OUTPUT_LINES} lines]`;
28459
+ }
28460
+ return { text, truncated };
28461
+ }
28462
+ function parseSshConfig(configPath) {
28463
+ const targetPath = configPath ?? join16(homedir2(), ".ssh", "config");
28464
+ if (!existsSync13(targetPath)) {
28465
+ return [];
28466
+ }
28467
+ try {
28468
+ const content = readFileSync11(targetPath, "utf-8");
28469
+ const lines = content.split("\n");
28470
+ const hosts = [];
28471
+ let currentHosts = [];
28472
+ for (const rawLine of lines) {
28473
+ const line = rawLine.trim();
28474
+ if (!line || line.startsWith("#")) continue;
28475
+ const spaceIdx = line.search(/\s/);
28476
+ if (spaceIdx === -1) continue;
28477
+ const key = line.slice(0, spaceIdx).trim().toLowerCase();
28478
+ const value = line.slice(spaceIdx + 1).trim();
28479
+ if (key === "host") {
28480
+ const aliases = value.split(/\s+/).filter((a) => a !== "*");
28481
+ currentHosts = [];
28482
+ for (const alias of aliases) {
28483
+ const entry = { alias, identityFiles: [] };
28484
+ currentHosts.push(entry);
28485
+ hosts.push(entry);
28486
+ }
28487
+ } else if (currentHosts.length > 0) {
28488
+ for (const currentHost of currentHosts) {
28489
+ if (key === "hostname") {
28490
+ currentHost.hostName = value;
28491
+ } else if (key === "user") {
28492
+ currentHost.user = value;
28493
+ } else if (key === "port") {
28494
+ const p = Number.parseInt(value, 10);
28495
+ if (!Number.isNaN(p)) currentHost.port = p;
28496
+ } else if (key === "proxyjump") {
28497
+ currentHost.proxyJump = value;
28498
+ } else if (key === "identityfile") {
28499
+ currentHost.identityFiles = currentHost.identityFiles ?? [];
28500
+ currentHost.identityFiles.push(value);
28501
+ }
28502
+ }
28503
+ }
28504
+ }
28505
+ return hosts;
28506
+ } catch {
28507
+ return [];
28508
+ }
28509
+ }
28510
+ function resolveSshHostG(host, execFn = spawnSync3) {
28511
+ try {
28512
+ const result = execFn("ssh", ["-G", host], { encoding: "utf-8" });
28513
+ if (result.status !== 0 || !result.stdout) {
28514
+ return { alias: host, hostName: host };
28515
+ }
28516
+ const lines = String(result.stdout).split("\n");
28517
+ const info = { alias: host, identityFiles: [] };
28518
+ for (const rawLine of lines) {
28519
+ const line = rawLine.trim();
28520
+ if (!line) continue;
28521
+ const spaceIdx = line.indexOf(" ");
28522
+ if (spaceIdx === -1) continue;
28523
+ const key = line.slice(0, spaceIdx).toLowerCase();
28524
+ const value = line.slice(spaceIdx + 1).trim();
28525
+ if (key === "hostname") {
28526
+ info.hostName = value;
28527
+ } else if (key === "user") {
28528
+ info.user = value;
28529
+ } else if (key === "port") {
28530
+ const p = Number.parseInt(value, 10);
28531
+ if (!Number.isNaN(p)) info.port = p;
28532
+ } else if (key === "proxyjump") {
28533
+ if (value && value !== "none") info.proxyJump = value;
28534
+ } else if (key === "identityfile") {
28535
+ info.identityFiles = info.identityFiles ?? [];
28536
+ info.identityFiles.push(value);
28537
+ }
28538
+ }
28539
+ return info;
28540
+ } catch {
28541
+ return { alias: host, hostName: host };
28542
+ }
28543
+ }
28544
+ function ensureSocketDir(socketDir = DEFAULT_SOCKET_DIR) {
28545
+ const resolved = resolve8(socketDir);
28546
+ if (!existsSync13(resolved)) {
28547
+ mkdirSync7(resolved, { recursive: true, mode: 448 });
28548
+ }
28549
+ return resolved;
28550
+ }
28551
+ function buildSshArgs(options) {
28552
+ const socketDir = ensureSocketDir(options.socketDir ?? DEFAULT_SOCKET_DIR);
28553
+ const controlPath = join16(socketDir, "%C");
28554
+ const persist2 = options.controlPersist ?? DEFAULT_CONTROL_PERSIST;
28555
+ const args = [
28556
+ "-o",
28557
+ `ControlMaster=auto`,
28558
+ "-o",
28559
+ `ControlPath=${controlPath}`,
28560
+ "-o",
28561
+ `ControlPersist=${persist2}`
28562
+ ];
28563
+ if (options.batchMode !== false) {
28564
+ args.push("-o", "BatchMode=yes");
28565
+ }
28566
+ if (options.strictHostKey !== false) {
28567
+ args.push("-o", "StrictHostKeyChecking=yes");
28568
+ }
28569
+ if (options.extraArgs) {
28570
+ args.push(...options.extraArgs);
28571
+ }
28572
+ assertPinnedSshHostKeyPolicy(args);
28573
+ args.push(options.host);
28574
+ return args;
28575
+ }
28576
+ function checkControlSocket(host, socketDir = DEFAULT_SOCKET_DIR, execFn = spawnSync3) {
28577
+ const resolvedDir = ensureSocketDir(socketDir);
28578
+ const controlPath = join16(resolvedDir, "%C");
28579
+ try {
28580
+ const result = execFn("ssh", ["-O", "check", "-o", `ControlPath=${controlPath}`, host], {
28581
+ encoding: "utf-8"
28582
+ });
28583
+ return result.status === 0;
28584
+ } catch {
28585
+ return false;
28586
+ }
28587
+ }
28588
+ function closeControlSocket(host, socketDir = DEFAULT_SOCKET_DIR, execFn = spawnSync3) {
28589
+ const resolvedDir = ensureSocketDir(socketDir);
28590
+ const controlPath = join16(resolvedDir, "%C");
28591
+ try {
28592
+ const result = execFn("ssh", ["-O", "stop", "-o", `ControlPath=${controlPath}`, host], {
28593
+ encoding: "utf-8"
28594
+ });
28595
+ return result.status === 0;
28596
+ } catch {
28597
+ return false;
28598
+ }
28599
+ }
28600
+ function pruneSocketDir(socketDir = DEFAULT_SOCKET_DIR) {
28601
+ const resolvedDir = ensureSocketDir(socketDir);
28602
+ let removed = 0;
28603
+ try {
28604
+ const entries = readdirSync5(resolvedDir);
28605
+ for (const entry of entries) {
28606
+ const fullPath = join16(resolvedDir, entry);
28607
+ try {
28608
+ const stat = statSync4(fullPath);
28609
+ if (stat.isSocket()) {
28610
+ rmSync2(fullPath, { force: true });
28611
+ removed++;
28612
+ }
28613
+ } catch {
28614
+ }
28615
+ }
28616
+ } catch {
28617
+ }
28618
+ return removed;
28619
+ }
28620
+ function executeSshRun(params) {
28621
+ const startTime = Date.now();
28622
+ const execSyncFn = params.execFn ?? spawnSync3;
28623
+ if (params.action === "info") {
28624
+ if (params.host) {
28625
+ const hostInfo = resolveSshHostG(params.host, execSyncFn);
28626
+ return {
28627
+ ok: true,
28628
+ action: "info",
28629
+ host: params.host,
28630
+ resolvedHost: hostInfo.hostName ?? params.host,
28631
+ user: hostInfo.user,
28632
+ port: hostInfo.port,
28633
+ hosts: [hostInfo],
28634
+ durationMs: Date.now() - startTime
28635
+ };
28636
+ }
28637
+ const discovered = parseSshConfig();
28638
+ return {
28639
+ ok: true,
28640
+ action: "info",
28641
+ hosts: discovered,
28642
+ durationMs: Date.now() - startTime
28643
+ };
28644
+ }
28645
+ if (!params.host) {
28646
+ return {
28647
+ ok: false,
28648
+ action: params.action,
28649
+ error: 'Parameter "host" is required for command and file actions.',
28650
+ durationMs: Date.now() - startTime
28651
+ };
28652
+ }
28653
+ const host = params.host;
28654
+ const socketDir = params.socket_dir ?? DEFAULT_SOCKET_DIR;
28655
+ const wasSocketActive = checkControlSocket(host, socketDir, execSyncFn);
28656
+ if (params.action === "command") {
28657
+ if (!params.command) {
28658
+ return {
28659
+ ok: false,
28660
+ action: "command",
28661
+ host,
28662
+ error: 'Parameter "command" is required for command action.',
28663
+ durationMs: Date.now() - startTime
28664
+ };
28665
+ }
28666
+ try {
28667
+ assertCommandSeatbelt(params.command);
28668
+ } catch (err) {
28669
+ return {
28670
+ ok: false,
28671
+ action: "command",
28672
+ host,
28673
+ error: err.message,
28674
+ durationMs: Date.now() - startTime
28675
+ };
28676
+ }
28677
+ let remoteCommand = params.command;
28678
+ let inputStdin = void 0;
28679
+ if (params.sudo) {
28680
+ const sudoPwd = params.sudo_password ?? params.password;
28681
+ if (sudoPwd) {
28682
+ inputStdin = `${sudoPwd}
28683
+ `;
28684
+ remoteCommand = `sudo -S -p '' -- sh -c ${JSON.stringify(params.command)}`;
28685
+ } else {
28686
+ remoteCommand = `sudo -- sh -c ${JSON.stringify(params.command)}`;
28687
+ }
28688
+ }
28689
+ const useSshPass = Boolean(params.password);
28690
+ const sshArgs = buildSshArgs({
28691
+ host,
28692
+ socketDir,
28693
+ controlPersist: params.control_persist,
28694
+ batchMode: !useSshPass,
28695
+ strictHostKey: params.strict_host_key
28696
+ });
28697
+ sshArgs.push("--", remoteCommand);
28698
+ const spawnEnv = { ...process.env };
28699
+ let binary = "ssh";
28700
+ let finalArgs = sshArgs;
28701
+ if (useSshPass && params.password) {
28702
+ binary = "sshpass";
28703
+ finalArgs = ["-e", "ssh", ...sshArgs];
28704
+ spawnEnv.SSHPASS = params.password;
28705
+ }
28706
+ try {
28707
+ const result = execSyncFn(binary, finalArgs, {
28708
+ encoding: "utf-8",
28709
+ env: spawnEnv,
28710
+ input: inputStdin,
28711
+ timeout: params.timeout_ms ?? 12e4,
28712
+ maxBuffer: 10 * 1024 * 1024
28713
+ });
28714
+ const stdoutRaw = String(result.stdout || "");
28715
+ const stderrRaw = String(result.stderr || "");
28716
+ const sanitizedStderr = stderrRaw.replace(/\[sudo\] password for [^:]+:\s*/gi, "");
28717
+ const stdoutTrunc = truncateSshOutput(stdoutRaw);
28718
+ const stderrTrunc = truncateSshOutput(sanitizedStderr);
28719
+ return {
28720
+ ok: result.status === 0,
28721
+ action: "command",
28722
+ host,
28723
+ exitCode: result.status ?? 1,
28724
+ stdout: stdoutTrunc.text,
28725
+ stderr: stderrTrunc.text,
28726
+ truncated: stdoutTrunc.truncated || stderrTrunc.truncated,
28727
+ socketReused: wasSocketActive,
28728
+ durationMs: Date.now() - startTime,
28729
+ error: result.error ? result.error.message : void 0
28730
+ };
28731
+ } catch (err) {
28732
+ return {
28733
+ ok: false,
28734
+ action: "command",
28735
+ host,
28736
+ error: err.message,
28737
+ durationMs: Date.now() - startTime
28738
+ };
28739
+ }
28740
+ }
28741
+ if (params.action === "file") {
28742
+ if (!params.file_path) {
28743
+ return {
28744
+ ok: false,
28745
+ action: "file",
28746
+ host,
28747
+ error: 'Parameter "file_path" is required for file action.',
28748
+ durationMs: Date.now() - startTime
28749
+ };
28750
+ }
28751
+ const filePath = params.file_path;
28752
+ const op = params.file_op ?? "write";
28753
+ if (op === "read") {
28754
+ const readCmd = params.sudo ? `sudo cat ${JSON.stringify(filePath)}` : `cat ${JSON.stringify(filePath)}`;
28755
+ return executeSshRun({
28756
+ ...params,
28757
+ action: "command",
28758
+ command: readCmd
28759
+ });
28760
+ }
28761
+ const content = params.file_content ?? "";
28762
+ const redirectOp = op === "append" ? ">>" : ">";
28763
+ const writeCmd = params.sudo ? `sudo tee ${op === "append" ? "-a " : ""}${JSON.stringify(filePath)} > /dev/null` : `cat ${redirectOp} ${JSON.stringify(filePath)}`;
28764
+ const useSshPass = Boolean(params.password);
28765
+ const sshArgs = buildSshArgs({
28766
+ host,
28767
+ socketDir,
28768
+ controlPersist: params.control_persist,
28769
+ batchMode: !useSshPass,
28770
+ strictHostKey: params.strict_host_key
28771
+ });
28772
+ sshArgs.push("--", writeCmd);
28773
+ const spawnEnv = { ...process.env };
28774
+ let binary = "ssh";
28775
+ let finalArgs = sshArgs;
28776
+ if (useSshPass && params.password) {
28777
+ binary = "sshpass";
28778
+ finalArgs = ["-e", "ssh", ...sshArgs];
28779
+ spawnEnv.SSHPASS = params.password;
28780
+ }
28781
+ try {
28782
+ const result = execSyncFn(binary, finalArgs, {
28783
+ encoding: "utf-8",
28784
+ env: spawnEnv,
28785
+ input: content,
28786
+ timeout: params.timeout_ms ?? 6e4
28787
+ });
28788
+ return {
28789
+ ok: result.status === 0,
28790
+ action: "file",
28791
+ host,
28792
+ exitCode: result.status ?? 1,
28793
+ stdout: String(result.stdout || ""),
28794
+ stderr: String(result.stderr || ""),
28795
+ fileProcessed: filePath,
28796
+ bytesProcessed: Buffer.byteLength(content, "utf-8"),
28797
+ socketReused: wasSocketActive,
28798
+ durationMs: Date.now() - startTime,
28799
+ error: result.error ? result.error.message : void 0
28800
+ };
28801
+ } catch (err) {
28802
+ return {
28803
+ ok: false,
28804
+ action: "file",
28805
+ host,
28806
+ error: err.message,
28807
+ durationMs: Date.now() - startTime
28808
+ };
28809
+ }
28810
+ }
28811
+ return {
28812
+ ok: false,
28813
+ action: params.action,
28814
+ error: `Unknown action: ${params.action}`,
28815
+ durationMs: Date.now() - startTime
28816
+ };
28817
+ }
28818
+
28819
+ // plugins/kxm/src/subagent-control.ts
28820
+ import { randomUUID as randomUUID5 } from "node:crypto";
28821
+ var SUBAGENT_TYPES = Object.freeze([
28822
+ "general",
28823
+ "Explore",
28824
+ "Plan",
28825
+ "Reviewer",
28826
+ "Auditor"
28827
+ ]);
28828
+ var DEFAULT_SUBAGENT_MODELS = Object.freeze({
28829
+ general: "grok/grok-4.6",
28830
+ Explore: "openrouter/qwen/qwen3-coder-plus",
28831
+ Plan: "claude/fable",
28832
+ Reviewer: "openai/gpt-5.6-sol",
28833
+ Auditor: "claude/fable"
28834
+ });
28835
+ function narrowSubagentTools(requestedTools, parentTools) {
28836
+ if (!requestedTools || requestedTools.length === 0) {
28837
+ return parentTools ? [...parentTools] : ["read", "grep", "find"];
28838
+ }
28839
+ if (!parentTools || parentTools.length === 0) {
28840
+ return [...requestedTools];
28841
+ }
28842
+ const parentSet = new Set(parentTools);
28843
+ const narrowed = [];
28844
+ for (const tool of requestedTools) {
28845
+ if (parentSet.has(tool)) {
28846
+ narrowed.push(tool);
28847
+ }
28848
+ }
28849
+ if (narrowed.length === 0 && requestedTools.length > 0) {
28850
+ throw new Error(
28851
+ `Cannot spawn subagent: requested tools [${requestedTools.join(", ")}] expand beyond parent capabilities.`
28852
+ );
28853
+ }
28854
+ return narrowed;
28855
+ }
28856
+ var SubagentManager = class {
28857
+ subagents = /* @__PURE__ */ new Map();
28858
+ /**
28859
+ * Spawns a new managed subagent with strict capability boundaries.
28860
+ */
28861
+ spawn(params) {
28862
+ if (!params.prompt || !params.prompt.trim()) {
28863
+ throw new Error('Subagent "prompt" is required.');
28864
+ }
28865
+ if (!params.description || !params.description.trim()) {
28866
+ throw new Error('Subagent "description" is required.');
28867
+ }
28868
+ const type = params.type ?? "general";
28869
+ const model = params.model ?? DEFAULT_SUBAGENT_MODELS[type] ?? "grok/grok-4.6";
28870
+ const thinking = params.thinking ?? "low";
28871
+ const allowedTools = narrowSubagentTools(params.allowed_tools, params.parent_tools);
28872
+ const id = `ag_${randomUUID5().replaceAll("-", "").slice(0, 10)}`;
28873
+ const now = (/* @__PURE__ */ new Date()).toISOString();
28874
+ const record2 = {
28875
+ id,
28876
+ description: params.description.trim(),
28877
+ type,
28878
+ model,
28879
+ thinking,
28880
+ allowedTools,
28881
+ status: params.background === false ? "completed" : "running",
28882
+ turnsMax: params.turns ?? 10,
28883
+ turnsCompleted: 0,
28884
+ prompt: params.prompt.trim(),
28885
+ createdAt: now,
28886
+ updatedAt: now,
28887
+ steeringMessages: []
28888
+ };
28889
+ this.subagents.set(id, record2);
28890
+ return record2;
28891
+ }
28892
+ /**
28893
+ * Dispatches an action from the `agent_control` tool.
28894
+ */
28895
+ control(params) {
28896
+ const action = params.action;
28897
+ if (action === "info") {
28898
+ const kind = params.kind ?? "active";
28899
+ if (kind === "types") {
28900
+ return {
28901
+ ok: true,
28902
+ action: "info",
28903
+ types: SUBAGENT_TYPES
28904
+ };
28905
+ }
28906
+ if (kind === "models") {
28907
+ return {
28908
+ ok: true,
28909
+ action: "info",
28910
+ result: JSON.stringify(DEFAULT_SUBAGENT_MODELS)
28911
+ };
28912
+ }
28913
+ const active = Array.from(this.subagents.values()).map((ag) => ({
28914
+ id: ag.id,
28915
+ description: ag.description,
28916
+ type: ag.type,
28917
+ status: ag.status
28918
+ }));
28919
+ return {
28920
+ ok: true,
28921
+ action: "info",
28922
+ activeAgents: active
28923
+ };
28924
+ }
28925
+ if (!params.agent_id) {
28926
+ return {
28927
+ ok: false,
28928
+ action,
28929
+ error: 'Parameter "agent_id" is required for result, steer, and stop actions.'
28930
+ };
28931
+ }
28932
+ const agent = this.subagents.get(params.agent_id);
28933
+ if (!agent) {
28934
+ return {
28935
+ ok: false,
28936
+ action,
28937
+ agent_id: params.agent_id,
28938
+ error: `Subagent "${params.agent_id}" not found.`
28939
+ };
28940
+ }
28941
+ if (action === "result") {
28942
+ return {
28943
+ ok: true,
28944
+ action: "result",
28945
+ agent_id: agent.id,
28946
+ status: agent.status,
28947
+ result: agent.output ?? `[Subagent is currently ${agent.status}]`
28948
+ };
28949
+ }
28950
+ if (action === "steer") {
28951
+ if (!params.message || !params.message.trim()) {
28952
+ return {
28953
+ ok: false,
28954
+ action: "steer",
28955
+ agent_id: agent.id,
28956
+ error: 'Parameter "message" is required for steer action.'
28957
+ };
28958
+ }
28959
+ if (agent.status === "completed" || agent.status === "stopped" || agent.status === "failed") {
28960
+ return {
28961
+ ok: false,
28962
+ action: "steer",
28963
+ agent_id: agent.id,
28964
+ error: `Cannot steer subagent "${agent.id}" because it is already ${agent.status}.`
28965
+ };
28966
+ }
28967
+ agent.steeringMessages.push({
28968
+ text: params.message.trim(),
28969
+ injectedAt: (/* @__PURE__ */ new Date()).toISOString(),
28970
+ processed: false
28971
+ });
28972
+ agent.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
28973
+ return {
28974
+ ok: true,
28975
+ action: "steer",
28976
+ agent_id: agent.id,
28977
+ status: agent.status,
28978
+ steered: true
28979
+ };
28980
+ }
28981
+ if (action === "stop") {
28982
+ agent.status = "stopped";
28983
+ agent.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
28984
+ return {
28985
+ ok: true,
28986
+ action: "stop",
28987
+ agent_id: agent.id,
28988
+ status: "stopped",
28989
+ stopped: true
28990
+ };
28991
+ }
28992
+ return {
28993
+ ok: false,
28994
+ action,
28995
+ error: `Unknown control action "${action}".`
28996
+ };
28997
+ }
28998
+ /**
28999
+ * Retrieves an agent record by ID.
29000
+ */
29001
+ get(agentId) {
29002
+ return this.subagents.get(agentId);
29003
+ }
29004
+ /**
29005
+ * Marks a subagent as completed with output.
29006
+ */
29007
+ complete(agentId, output) {
29008
+ const agent = this.subagents.get(agentId);
29009
+ if (agent) {
29010
+ agent.status = "completed";
29011
+ agent.output = output;
29012
+ agent.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
29013
+ }
29014
+ }
29015
+ /**
29016
+ * Returns all active running subagents.
29017
+ */
29018
+ listActive() {
29019
+ return Array.from(this.subagents.values()).filter(
29020
+ (ag) => ag.status === "running" || ag.status === "pending" || ag.status === "blocked"
29021
+ );
29022
+ }
29023
+ };
28421
29024
  export {
28422
29025
  BUILTIN_HARNESSES,
28423
29026
  BUILTIN_HARNESS_IDS,
28424
29027
  CANDIDATE_SCHEMA,
29028
+ DEFAULT_CONTROL_PERSIST,
28425
29029
  DEFAULT_HARNESS,
28426
29030
  DEFAULT_LOG_MAX_BYTES,
28427
29031
  DEFAULT_LOG_MAX_FILES,
28428
29032
  DEFAULT_MODES_CONFIG,
29033
+ DEFAULT_SOCKET_DIR,
29034
+ DEFAULT_SUBAGENT_MODELS,
28429
29035
  IMPROVEMENT_REPORT_SCHEMA,
28430
29036
  IMPROVEMENT_REPORT_V1_SCHEMA,
28431
29037
  LOG_LEVEL_PRIORITY,
29038
+ MAX_SSH_OUTPUT_BYTES,
29039
+ MAX_SSH_OUTPUT_LINES,
28432
29040
  NATIVE_HARNESS_PROVIDERS,
28433
29041
  PI_ALLOWED_PROVIDERS,
28434
29042
  PI_NATIVE_BRAKE_PROVIDERS,
28435
29043
  PiSession,
28436
29044
  SAFE_HARNESS_COMMAND_ID,
29045
+ SUBAGENT_TYPES,
28437
29046
  SteelClient,
29047
+ SubagentManager,
28438
29048
  VIEWPORT_PRESETS,
28439
29049
  VNEXT_ABSENT_MEMORY_REVISION,
28440
29050
  VNEXT_EVENT_STORE_SCHEMA_VERSION,
@@ -28448,13 +29058,16 @@ export {
28448
29058
  assertVnextConfigError,
28449
29059
  backupDatabaseFile,
28450
29060
  buildImprovementReport,
29061
+ buildSshArgs,
28451
29062
  calculatePromptFootprint,
28452
29063
  cancelVnextRun,
29064
+ checkControlSocket,
28453
29065
  checkIntegrity,
28454
29066
  checkMemoryRevisionDrift,
28455
29067
  checkedParent,
28456
29068
  checkpointWal,
28457
29069
  classifyCandidateKind,
29070
+ closeControlSocket,
28458
29071
  closeVnextRuntimeContext,
28459
29072
  computeGateEvidenceOutcome,
28460
29073
  computeVnextMemoryRevision,
@@ -28467,10 +29080,12 @@ export {
28467
29080
  defaultSpawn,
28468
29081
  discoverProjectStores,
28469
29082
  eligibleHarnesses,
29083
+ ensureSocketDir,
28470
29084
  ensureVnextSupervisor,
28471
29085
  ensureWalJournalMode,
28472
29086
  estimateTokens,
28473
29087
  evaluatePromotionPolicy,
29088
+ executeSshRun,
28474
29089
  fileSha256,
28475
29090
  findWinNpmInnerExe,
28476
29091
  foldStoredVnextRun,
@@ -28492,6 +29107,7 @@ export {
28492
29107
  isVnextRuntimeContextClosed,
28493
29108
  isWindowsHarnessShim,
28494
29109
  loadModesConfig,
29110
+ narrowSubagentTools,
28495
29111
  newVnextAssignmentId,
28496
29112
  newVnextAttemptId,
28497
29113
  newVnextCommandId,
@@ -28509,6 +29125,7 @@ export {
28509
29125
  parseGenericOneShotUsage,
28510
29126
  parseGrokOneShotUsage,
28511
29127
  parseKimiOneShotUsage,
29128
+ parseSshConfig,
28512
29129
  persistVnextRunState,
28513
29130
  planHarnessUpdate,
28514
29131
  probeHarnessAssignment,
@@ -28516,6 +29133,7 @@ export {
28516
29133
  probeHarnesses,
28517
29134
  probeHarnessesForModel,
28518
29135
  projectRuntimeKey,
29136
+ pruneSocketDir,
28519
29137
  readVnextRunStatus,
28520
29138
  readVnextSupervisorToken,
28521
29139
  rebuildVnextRunProjection,
@@ -28524,6 +29142,7 @@ export {
28524
29142
  resolveActiveMode,
28525
29143
  resolveDispatchStatus,
28526
29144
  resolvePassCliApiKey,
29145
+ resolveSshHostG,
28527
29146
  resolveSteelConfig,
28528
29147
  resolveViewportDimensions,
28529
29148
  restoreBackup,
@@ -28534,6 +29153,7 @@ export {
28534
29153
  sanitizeLogOutput,
28535
29154
  startVnextRuntimeSupervisor,
28536
29155
  tableColumns,
29156
+ truncateSshOutput,
28537
29157
  userTables,
28538
29158
  validateHarnessModelPair,
28539
29159
  verifyExpectedTables,