@openagents-org/agent-launcher 0.2.212 → 0.2.213

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openagents-org/agent-launcher",
3
- "version": "0.2.212",
3
+ "version": "0.2.213",
4
4
  "description": "OpenAgents Launcher — install, configure, and run AI coding agents from your terminal",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -384,6 +384,67 @@ function classifyKimiError(info) {
384
384
  return { kind: 'error', userMessage: `Kimi Code CLI ${why}.` };
385
385
  }
386
386
 
387
+ // ---------------------------------------------------------------------------
388
+ // Workspace tools (MCP) through a private Kimi home
389
+ // ---------------------------------------------------------------------------
390
+
391
+ /**
392
+ * Kimi Code has no flag for an MCP config and ignores a project-level
393
+ * `.kimi-code/mcp.json`; it reads MCP servers from `$KIMI_CODE_HOME/mcp.json`
394
+ * (2.4.1). Each agent therefore runs with its own Kimi home under
395
+ * ~/.openagents, so the workspace server can be added without editing the
396
+ * user's ~/.kimi-code. Kimi passes its whole environment to stdio MCP
397
+ * servers, so the file names only the command: the token, workspace and
398
+ * channel of each run travel in the environment (see buildKimiWorkspaceEnv).
399
+ */
400
+ const KIMI_MCP_SERVER_NAME = 'openagents-workspace';
401
+
402
+ /**
403
+ * Entries of the user's Kimi home a private home links back to: the
404
+ * `kimi login` credentials (a directory, so token refreshes land in the
405
+ * user's home) and config.toml (providers and default model for the
406
+ * no-API-key route).
407
+ */
408
+ const KIMI_HOME_LINKS = [
409
+ { name: 'credentials', dir: true },
410
+ { name: 'config.toml', dir: false },
411
+ ];
412
+
413
+ /** Directory name of an agent's private Kimi home: readable, unique per workspace+agent. */
414
+ function kimiHomeName(workspaceId, agentName) {
415
+ const raw = `${workspaceId == null ? '' : workspaceId}\u0000${agentName == null ? '' : agentName}`;
416
+ const hash = crypto.createHash('sha256').update(raw).digest('hex').slice(0, 8);
417
+ const slug = (v) => String(v == null ? '' : v).toLowerCase()
418
+ .replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 32) || 'agent';
419
+ return `${slug(workspaceId)}_${slug(agentName)}-${hash}`;
420
+ }
421
+
422
+ /**
423
+ * The private home's mcp.json: the user's own MCP servers (so a private home
424
+ * loses nothing the user configured) plus the workspace server, which always
425
+ * wins its name. An unreadable user file contributes nothing.
426
+ */
427
+ function buildKimiMcpConfig(userConfig, server) {
428
+ const base = userConfig && typeof userConfig === 'object' && !Array.isArray(userConfig) ? userConfig : {};
429
+ const servers = base.mcpServers && typeof base.mcpServers === 'object' && !Array.isArray(base.mcpServers)
430
+ ? { ...base.mcpServers }
431
+ : {};
432
+ servers[KIMI_MCP_SERVER_NAME] = server;
433
+ return { ...base, mcpServers: servers };
434
+ }
435
+
436
+ /** What the workspace MCP server reads from its environment (cli.js `mcp-server`). */
437
+ function buildKimiWorkspaceEnv({ token, workspaceId, channel, agentName, endpoint }) {
438
+ const env = {
439
+ OPENAGENTS_WORKSPACE_ID: String(workspaceId || ''),
440
+ OPENAGENTS_CHANNEL_NAME: String(channel || 'general'),
441
+ OPENAGENTS_AGENT_NAME: String(agentName || 'agent'),
442
+ };
443
+ if (endpoint) env.OPENAGENTS_ENDPOINT = String(endpoint);
444
+ if (token) env.OA_WORKSPACE_TOKEN = String(token);
445
+ return env;
446
+ }
447
+
387
448
  module.exports = {
388
449
  parseKimiVersion,
389
450
  classifyKimiVersion,
@@ -402,4 +463,9 @@ module.exports = {
402
463
  DEFAULT_MAX_COMPLETION_TOKENS,
403
464
  EXIT_PERMANENT,
404
465
  EXIT_TRANSIENT,
466
+ KIMI_MCP_SERVER_NAME,
467
+ KIMI_HOME_LINKS,
468
+ kimiHomeName,
469
+ buildKimiMcpConfig,
470
+ buildKimiWorkspaceEnv,
405
471
  };
@@ -19,7 +19,17 @@
19
19
  * OpenAI-compatible chat completions against KIMI_BASE_URL (inherited from
20
20
  * LlmDirectAdapter).
21
21
  *
22
- * Verified against Kimi Code CLI v0.39.1. NOTE: the legacy Python `kimi-cli`
22
+ * - workspace tools: the CLI reads MCP servers only from
23
+ * `$KIMI_CODE_HOME/mcp.json`, so each agent runs with a private Kimi home
24
+ * (~/.openagents/kimi-homes/<agent>/) that adds the workspace MCP server to
25
+ * the user's own servers and links their `kimi login` credentials and
26
+ * config.toml back in. The token, workspace and channel reach the MCP
27
+ * server through the environment, never through a file.
28
+ * - no sandbox: print mode approves every tool call and the CLI has no
29
+ * filesystem boundary, so the agent can write outside its working
30
+ * directory. That is the CLI's own model, not something this adapter adds.
31
+ *
32
+ * Verified against Kimi Code CLI v0.39.1 and 2.4.1. NOTE: the legacy Python `kimi-cli`
23
33
  * (PyPI) also installs a `kimi` binary but reports 1.x versions and has a
24
34
  * different interface — it is detected and NOT driven.
25
35
  */
@@ -49,6 +59,11 @@ const {
49
59
  classifyKimiVersion,
50
60
  classifyKimiError,
51
61
  encodeKimiWorkDirKey,
62
+ KIMI_MCP_SERVER_NAME,
63
+ KIMI_HOME_LINKS,
64
+ kimiHomeName,
65
+ buildKimiMcpConfig,
66
+ buildKimiWorkspaceEnv,
52
67
  } = require('./kimi-stream');
53
68
 
54
69
  const IS_WINDOWS = process.platform === 'win32';
@@ -255,10 +270,14 @@ class KimiAdapter extends LlmDirectAdapter {
255
270
  if (!proc || proc.exitCode !== null) return;
256
271
  try {
257
272
  if (IS_WINDOWS) {
258
- try { proc.kill('SIGINT'); } catch {}
259
- const exited = await this._waitExit(proc, 1500);
260
- if (!exited) {
261
- try { execSync(`taskkill /F /T /PID ${proc.pid}`, { timeout: 5000, windowsHide: true }); } catch {}
273
+ // Tree first. On Windows proc.kill() is TerminateProcess whatever the
274
+ // signal, so "SIGINT, then taskkill /T if it is still alive" never
275
+ // reached taskkill — and once kimi is dead its shell commands can no
276
+ // longer be found through it: a Stop left them running.
277
+ try { execSync(`taskkill /F /T /PID ${proc.pid}`, { timeout: 5000, windowsHide: true }); } catch {}
278
+ if (!(await this._waitExit(proc, 1500))) {
279
+ try { proc.kill(); } catch {}
280
+ await this._waitExit(proc, 1000);
262
281
  }
263
282
  } else {
264
283
  try { process.kill(-proc.pid, 'SIGINT'); } catch { try { proc.kill('SIGINT'); } catch {} }
@@ -456,6 +475,13 @@ class KimiAdapter extends LlmDirectAdapter {
456
475
  if (this._mode === 'plan') {
457
476
  lines.push('You are in PLAN mode: investigate and propose a plan; do not modify files.');
458
477
  }
478
+ if (this._workspaceToolsReady) {
479
+ lines.push(
480
+ `For anything in the OpenAgents workspace — chat history, files, uploads, knowledge, todos — use the ` +
481
+ `\`workspace_*\` tools (MCP server "${KIMI_MCP_SERVER_NAME}"). They are already signed in: never look for, ` +
482
+ 'print or use a workspace token, and do not call the workspace HTTP API yourself.',
483
+ );
484
+ }
459
485
  lines.push('Work in the current working directory. Reply concisely. The user request follows:');
460
486
  return lines.join('\n');
461
487
  }
@@ -584,6 +610,9 @@ class KimiAdapter extends LlmDirectAdapter {
584
610
 
585
611
  // Resuming → Kimi already has history, send the bare turn. Fresh →
586
612
  // prepend a context header (+ recap when available).
613
+ // Decided before the prompt is built: the header only promises the
614
+ // workspace tools when this run will actually have them.
615
+ this._workspaceToolsReady = !!this._prepareKimiHome();
587
616
  let prompt;
588
617
  if (resumeId) {
589
618
  prompt = content;
@@ -633,6 +662,92 @@ class KimiAdapter extends LlmDirectAdapter {
633
662
  }
634
663
  }
635
664
 
665
+ // ------------------------------------------------------------------
666
+ // Private Kimi home (workspace MCP tools)
667
+ // ------------------------------------------------------------------
668
+
669
+ /** This agent's own Kimi home. See KIMI_MCP_SERVER_NAME in kimi-stream.js. */
670
+ _kimiHome() {
671
+ return path.join(os.homedir(), '.openagents', 'kimi-homes', kimiHomeName(this.workspaceId, this.agentName));
672
+ }
673
+
674
+ /** The user's own Kimi home, which the private one links back to. */
675
+ _userKimiHome() {
676
+ const env = this.agentEnv || {};
677
+ return env.KIMI_CODE_HOME || process.env.KIMI_CODE_HOME || path.join(os.homedir(), '.kimi-code');
678
+ }
679
+
680
+ /**
681
+ * (Re)build the private home for one run and return its path, or null when
682
+ * it cannot be prepared — the run then goes ahead without workspace tools,
683
+ * exactly as before.
684
+ *
685
+ * Every run re-checks the links, so a `kimi login` done after the agent
686
+ * started is picked up, and rewrites mcp.json, so a change to the user's own
687
+ * MCP servers or to the agent's disabled modules applies at once.
688
+ */
689
+ _prepareKimiHome() {
690
+ const home = this._kimiHome();
691
+ try {
692
+ fs.mkdirSync(home, { recursive: true, mode: 0o700 });
693
+ const userHome = this._userKimiHome();
694
+ for (const { name, dir } of KIMI_HOME_LINKS) this._linkIntoKimiHome(path.join(userHome, name), path.join(home, name), dir);
695
+
696
+ const command = this._mcpServerCommand();
697
+ if (!command) {
698
+ this._log('Could not locate the OpenAgents CLI — workspace tools are unavailable this run');
699
+ return null;
700
+ }
701
+ let userConfig = null;
702
+ try { userConfig = JSON.parse(fs.readFileSync(path.join(userHome, 'mcp.json'), 'utf-8')); } catch {}
703
+ const config = buildKimiMcpConfig(userConfig, command);
704
+ const file = path.join(home, 'mcp.json');
705
+ const tmp = `${file}.${process.pid}.tmp`;
706
+ fs.writeFileSync(tmp, JSON.stringify(config, null, 2), { mode: 0o600 });
707
+ fs.renameSync(tmp, file);
708
+ return home;
709
+ } catch (e) {
710
+ this._log(`Could not prepare the private Kimi home (${redactSecrets(e && e.message)}) — workspace tools are unavailable this run`);
711
+ return null;
712
+ }
713
+ }
714
+
715
+ /**
716
+ * Point `dest` at `target` in the user's home. A directory is linked
717
+ * (a junction on Windows, which needs no privilege), so writes such as a
718
+ * credentials refresh land in the user's home. A file is symlinked on POSIX
719
+ * and copied on Windows, where file symlinks need Developer Mode. Anything
720
+ * already at `dest` that is not ours to replace is left alone.
721
+ */
722
+ _linkIntoKimiHome(target, dest, isDir) {
723
+ if (!fs.existsSync(target)) return;
724
+ let st = null;
725
+ try { st = fs.lstatSync(dest); } catch {}
726
+ if (st && st.isSymbolicLink()) {
727
+ let current = null;
728
+ try { current = fs.readlinkSync(dest); } catch {}
729
+ if (current && path.resolve(path.dirname(dest), current) === path.resolve(target)) return;
730
+ fs.rmSync(dest, { force: true });
731
+ } else if (st && !(IS_WINDOWS && !isDir && st.isFile())) {
732
+ return;
733
+ }
734
+ if (isDir) fs.symlinkSync(target, dest, IS_WINDOWS ? 'junction' : 'dir');
735
+ else if (IS_WINDOWS) fs.copyFileSync(target, dest);
736
+ else fs.symlinkSync(target, dest, 'file');
737
+ }
738
+
739
+ /** The stdio command that runs this package's workspace MCP server. */
740
+ _mcpServerCommand() {
741
+ const bin = path.resolve(__dirname, '..', '..', 'bin', 'agent-connector.js');
742
+ if (!fs.existsSync(bin)) return null;
743
+ const args = [bin, 'mcp-server'];
744
+ const disabled = this.disabledModules || new Set();
745
+ if (disabled.has('files')) args.push('--disable-files');
746
+ if (disabled.has('browser')) args.push('--disable-browser');
747
+ if (disabled.has('knowledge')) args.push('--disable-knowledge');
748
+ return { command: process.execPath, args };
749
+ }
750
+
636
751
  _dirExists(p) {
637
752
  try { return fs.statSync(p).isDirectory(); } catch { return false; }
638
753
  }
@@ -683,6 +798,17 @@ class KimiAdapter extends LlmDirectAdapter {
683
798
  // Stopped while this turn was being prepared: start nothing (no tokens).
684
799
  if (this._stoppedBeforeStart(channel)) return Promise.resolve({ userStopped: true });
685
800
  const { env: cleanEnv } = buildKimiEnv(this.agentEnv || process.env);
801
+ const kimiHome = this._prepareKimiHome();
802
+ if (kimiHome) {
803
+ cleanEnv.KIMI_CODE_HOME = kimiHome;
804
+ Object.assign(cleanEnv, buildKimiWorkspaceEnv({
805
+ token: this.token,
806
+ workspaceId: this.workspaceId,
807
+ channel,
808
+ agentName: this.agentName,
809
+ endpoint: this.endpoint,
810
+ }));
811
+ }
686
812
  const [cmd, ...spawnArgs] = this._spawnableCmd(kimiBin, args);
687
813
  // Before the spawn, so the session this run creates shows up as new.
688
814
  const sessionWatch = this._watchKimiSessions(cleanEnv, workingDir, args);
@@ -702,6 +828,7 @@ class KimiAdapter extends LlmDirectAdapter {
702
828
  const state = {
703
829
  ok: false,
704
830
  finalText: '',
831
+ pendingThought: '',
705
832
  sessionId: null,
706
833
  anyOutput: false,
707
834
  userStopped: false,
@@ -743,12 +870,21 @@ class KimiAdapter extends LlmDirectAdapter {
743
870
  for (const e of interpretKimiMessage(m)) {
744
871
  switch (e.kind) {
745
872
  case 'text':
873
+ // Held back until the turn moves on: the LAST text is the reply,
874
+ // posted once as the response rather than also as a thought.
746
875
  state.anyOutput = true;
876
+ if (state.pendingThought) {
877
+ try { await this.sendThinking(channel, state.pendingThought); } catch {}
878
+ }
879
+ state.pendingThought = e.text;
747
880
  state.finalText = e.text;
748
- try { await this.sendThinking(channel, e.text); } catch {}
749
881
  break;
750
882
  case 'tool_start':
751
883
  state.anyOutput = true;
884
+ if (state.pendingThought) {
885
+ try { await this.sendThinking(channel, state.pendingThought); } catch {}
886
+ state.pendingThought = '';
887
+ }
752
888
  try {
753
889
  await this.sendStatus(channel, e.preview ? `${e.name}: ${e.preview}` : e.name);
754
890
  } catch {}