scalix 1.5.1 → 1.6.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/dist/tools.js CHANGED
@@ -1,18 +1,54 @@
1
1
  import { tool } from './tool-helper.js';
2
2
  import { z } from 'zod';
3
- import { exec, spawn } from 'node:child_process';
3
+ import { exec, execFile, spawn } from 'node:child_process';
4
4
  import { promisify } from 'node:util';
5
5
  import fsSync from 'node:fs';
6
6
  import fs from 'node:fs/promises';
7
+ import os from 'node:os';
7
8
  import path from 'node:path';
8
9
  import { safeEvaluate } from './safe-math.js';
9
10
  import { sandboxPath, isBlockedCommand, detectInjection, sanitizeEnvForCommand, getShellInfo, isWithinRoot, getSandboxRoot } from './sandbox.js';
10
11
  import { DEFAULT_LIMITS } from './settings.js';
11
- import { TOOL_DEFAULTS, BINARY_DETECT_BUFFER_SIZE, isPrivateHost } from './constants.js';
12
+ import { TOOL_DEFAULTS, BINARY_DETECT_BUFFER_SIZE } from './constants.js';
12
13
  import { computeDiff, formatDiff } from './diff.js';
14
+ import { normalizeMcpConfig, validateMcpUrl } from './mcp.js';
15
+ import { buildSandboxWrap, materializeWrap } from './command-sandbox.js';
13
16
  let _limits = DEFAULT_LIMITS;
14
17
  export function setToolLimits(limits) { _limits = limits; }
18
+ // OS-level command sandbox (command-sandbox.ts). Off until something wires it:
19
+ // the Agent constructor pushes the resolved config mode here, so every front
20
+ // end (CLI, IPC, headless) inherits the same policy with no per-entry plumbing.
21
+ let _sandboxMode = 'off';
22
+ export function setCommandSandboxMode(mode) { _sandboxMode = mode; }
23
+ export function getCommandSandboxMode() { return _sandboxMode; }
15
24
  const execAsync = promisify(exec);
25
+ const execFileAsync = promisify(execFile);
26
+ /**
27
+ * Run a command string inside the OS sandbox when enabled. Returns the wrap's
28
+ * exec argv, or null when the sandbox is off/unavailable (with a reason).
29
+ * The profile file (darwin) is written next to the process and unlinked by the
30
+ * caller after the child exits.
31
+ */
32
+ async function sandboxedArgv(command, workingDir) {
33
+ if (_sandboxMode === 'off')
34
+ return { error: 'sandbox disabled' };
35
+ const shell = getShellInfo();
36
+ const built = buildSandboxWrap(_sandboxMode, workingDir, shell);
37
+ if (!built.ok)
38
+ return { error: built.error };
39
+ let profilePath;
40
+ if (built.wrap.profile) {
41
+ try {
42
+ profilePath = path.join(os.tmpdir(), `scalix-sandbox-${process.pid}-${Date.now()}.sb`);
43
+ await fs.writeFile(profilePath, built.wrap.profile, { mode: 0o600 });
44
+ }
45
+ catch (err) {
46
+ return { error: `could not write the sandbox profile: ${err.message}` };
47
+ }
48
+ }
49
+ const { execPath, args } = materializeWrap(built.wrap, command, profilePath);
50
+ return { execPath, args, profilePath };
51
+ }
16
52
  let persistentCwd = process.cwd();
17
53
  export function getPersistentCwd() { return persistentCwd; }
18
54
  export function setPersistentCwd(dir) { persistentCwd = dir; }
@@ -93,12 +129,25 @@ export const runCommandTool = tool({
93
129
  }
94
130
  const shell = getShellInfo();
95
131
  if (runInBg) {
96
- const child = spawn(shell.path, [...shell.args, command], {
97
- detached: true,
98
- stdio: ['ignore', 'pipe', 'pipe'],
99
- env: sanitizeEnvForCommand(),
100
- cwd: workingDir,
101
- });
132
+ const bg = _sandboxMode === 'off'
133
+ ? null
134
+ : await sandboxedArgv(command, workingDir);
135
+ if (bg && 'error' in bg) {
136
+ return { error: `Command sandbox unavailable: ${bg.error}`, exitCode: -1 };
137
+ }
138
+ const child = bg
139
+ ? spawn(bg.execPath, bg.args, {
140
+ detached: true,
141
+ stdio: ['ignore', 'pipe', 'pipe'],
142
+ env: sanitizeEnvForCommand(),
143
+ cwd: workingDir,
144
+ })
145
+ : spawn(shell.path, [...shell.args, command], {
146
+ detached: true,
147
+ stdio: ['ignore', 'pipe', 'pipe'],
148
+ env: sanitizeEnvForCommand(),
149
+ cwd: workingDir,
150
+ });
102
151
  if (!child.pid) {
103
152
  return { error: 'Failed to spawn background process: no PID assigned', exitCode: -1 };
104
153
  }
@@ -180,13 +229,40 @@ export const runCommandTool = tool({
180
229
  fullCommand = cwdProbe;
181
230
  }
182
231
  try {
183
- const { stdout, stderr } = await execAsync(fullCommand, {
232
+ let stdout;
233
+ let stderr;
234
+ const execOpts = {
184
235
  timeout: timeout ?? _limits.commandTimeoutMs,
185
236
  maxBuffer: TOOL_DEFAULTS.maxExecBufferDefault,
186
237
  env: sanitizeEnvForCommand(),
187
238
  cwd: workingDir,
188
239
  shell: shell.path,
189
- });
240
+ };
241
+ if (_sandboxMode === 'off') {
242
+ ({ stdout, stderr } = await execAsync(fullCommand, execOpts));
243
+ }
244
+ else {
245
+ // Kernel-enforced confinement: sandbox-exec (seatbelt) or bwrap execs
246
+ // the same shell with the same command string, so shell semantics are
247
+ // unchanged — what changes is what the child is allowed to touch.
248
+ const sb = await sandboxedArgv(fullCommand, workingDir);
249
+ if ('error' in sb) {
250
+ return { error: `Command sandbox unavailable: ${sb.error}`, exitCode: -1 };
251
+ }
252
+ try {
253
+ ({ stdout, stderr } = await execFileAsync(sb.execPath, sb.args, {
254
+ timeout: execOpts.timeout,
255
+ maxBuffer: execOpts.maxBuffer,
256
+ env: execOpts.env,
257
+ cwd: execOpts.cwd,
258
+ }));
259
+ }
260
+ finally {
261
+ if (sb.profilePath) {
262
+ fs.unlink(sb.profilePath).catch(() => { });
263
+ }
264
+ }
265
+ }
190
266
  if (cdTarget && fullCommand !== command) {
191
267
  const markerIdx = stdout.indexOf(CWD_MARKER);
192
268
  if (markerIdx !== -1) {
@@ -359,24 +435,21 @@ export const addMcpServerTool = tool({
359
435
  }),
360
436
  execute: async ({ label, url }) => {
361
437
  try {
362
- let parsedUrl;
363
- try {
364
- parsedUrl = new URL(url);
365
- }
366
- catch {
367
- return { success: false, error: `Invalid MCP server URL: "${url}" is not a valid URL` };
368
- }
369
- if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
370
- return { success: false, error: `Invalid MCP server URL: only http/https schemes are allowed (got ${parsedUrl.protocol})` };
371
- }
372
- if (isPrivateHost(parsedUrl.hostname)) {
373
- return { success: false, error: 'Blocked: MCP server URL points at localhost or a private network address' };
438
+ // Shared with the config-file and /mcp paths so all three refuse the
439
+ // same URLs — this check used to live only here, which is how the
440
+ // config file ended up being the way around it.
441
+ const blocked = validateMcpUrl(url);
442
+ if (blocked) {
443
+ return { success: false, error: `Invalid MCP server URL: ${blocked}` };
374
444
  }
375
445
  const mcpConfigPath = path.resolve(process.cwd(), 'mcp-services.json');
376
446
  let config = { mcpServers: [] };
377
447
  try {
378
448
  if (fsSync.existsSync(mcpConfigPath)) {
379
- const parsed = JSON.parse(fsSync.readFileSync(mcpConfigPath, 'utf-8'));
449
+ // Through normalizeMcpConfig, because the IDE panel writes the
450
+ // object-map dialect. Blindly resetting a non-array mcpServers to []
451
+ // here would silently delete every server the user configured there.
452
+ const parsed = normalizeMcpConfig(JSON.parse(fsSync.readFileSync(mcpConfigPath, 'utf-8')));
380
453
  if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
381
454
  config = parsed;
382
455
  if (!Array.isArray(config.mcpServers))
@@ -385,6 +458,9 @@ export const addMcpServerTool = tool({
385
458
  }
386
459
  }
387
460
  catch { }
461
+ if (config.mcpServers.some((s) => s?.serverLabel === label)) {
462
+ return { success: false, error: `An MCP server labelled "${label}" is already configured` };
463
+ }
388
464
  config.mcpServers.push({ serverLabel: label, serverUrl: url });
389
465
  await fs.writeFile(mcpConfigPath, JSON.stringify(config, null, 2), 'utf-8');
390
466
  return { success: true, message: `Added MCP server ${label} at ${url}` };
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Scalix Coder loads and executes code/config from the current project
5
5
  * directory — plugin handler modules (dynamic import), hooks (shell commands),
6
+ * MCP servers (a spawned process, or a URL we hand an environment secret to),
6
7
  * scoped rules (injected into the model context) and local settings overrides
7
8
  * (which can change permission mode / security). Opening the tool in an
8
9
  * untrusted / freshly-cloned repository must NOT silently run any of that.
@@ -43,7 +44,16 @@ function normalize(cwd) {
43
44
  export function hasProjectExecSurface(cwd = process.cwd()) {
44
45
  const candidates = ['mcp-services.json'];
45
46
  for (const dir of PROJECT_LOOKUP_DIRS) {
46
- candidates.push(path.join(dir, 'plugins'), path.join(dir, 'hooks.json'), path.join(dir, 'rules'), path.join(dir, 'settings.local.json'));
47
+ candidates.push(path.join(dir, 'plugins'), path.join(dir, 'hooks.json'),
48
+ // resolveMcpConfigPath() falls back to .scalix/mcp-services.json, so a
49
+ // repo can carry MCP config without a root-level file. Listing only the
50
+ // root filename meant an MCP-only clone looked inert and the user was
51
+ // never offered the trust prompt for the one thing it did have.
52
+ path.join(dir, 'mcp-services.json'), path.join(dir, 'rules'), path.join(dir, 'settings.local.json'),
53
+ // Command .md files may carry !`cmd` inline-bash expansions, which run
54
+ // shell commands — an exec surface like hooks, so they warrant the
55
+ // trust prompt too.
56
+ path.join(dir, 'commands'));
47
57
  }
48
58
  return candidates.some(rel => {
49
59
  try {
package/dist/worktree.js CHANGED
@@ -51,7 +51,7 @@ export async function createWorktree(agentId, basePath) {
51
51
  createdAt: Date.now(),
52
52
  };
53
53
  }
54
- export async function removeWorktree(info, basePath) {
54
+ export async function removeWorktree(info, basePath, options = {}) {
55
55
  try {
56
56
  await execFileAsync('git', ['worktree', 'remove', info.path, '--force'], {
57
57
  cwd: basePath,
@@ -68,14 +68,31 @@ export async function removeWorktree(info, basePath) {
68
68
  // best effort
69
69
  }
70
70
  }
71
+ // `git branch -d` refuses to delete a branch with unmerged commits — the
72
+ // safe default. Only fall back to `-D` when the caller explicitly asked for
73
+ // a forced delete; otherwise keep the branch so the sub-agent's commits
74
+ // stay recoverable.
71
75
  try {
72
- await execFileAsync('git', ['branch', '-D', info.branch], {
76
+ await execFileAsync('git', ['branch', '-d', info.branch], {
73
77
  cwd: basePath,
74
78
  timeout: 10_000,
75
79
  });
76
80
  }
77
81
  catch {
78
- // branch may already be deleted
82
+ if (options.forceBranch) {
83
+ try {
84
+ await execFileAsync('git', ['branch', '-D', info.branch], {
85
+ cwd: basePath,
86
+ timeout: 10_000,
87
+ });
88
+ }
89
+ catch {
90
+ // branch may already be deleted
91
+ }
92
+ }
93
+ else {
94
+ logger.info('Kept unmerged worktree branch for recovery', { agentId: info.agentId, branch: info.branch });
95
+ }
79
96
  }
80
97
  logger.info('Removed worktree', { agentId: info.agentId, path: info.path });
81
98
  }
@@ -109,8 +126,10 @@ export async function mergeWorktree(info, basePath, targetBranch) {
109
126
  return { merged: false, conflicts, commitCount: commits.length };
110
127
  }
111
128
  }
112
- catch {
113
- return { merged: true, commitCount: 0 };
129
+ catch (err) {
130
+ // The probe itself failed (detached HEAD, missing ref, timeout) — report
131
+ // a real failure instead of pretending the merge was a clean no-op.
132
+ return { merged: false, commitCount: 0, error: err?.message || String(err) };
114
133
  }
115
134
  }
116
135
  export async function listWorktrees(basePath) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "scalix",
3
- "version": "1.5.1",
3
+ "version": "1.6.0",
4
4
  "description": "AI coding agent for the terminal — edit code, run commands, and build with Scalix",
5
5
  "main": "dist/headless.js",
6
6
  "bin": {
@@ -17,6 +17,7 @@
17
17
  "start:headless": "tsx src/headless.ts",
18
18
  "dev": "tsx watch src/cli.tsx",
19
19
  "build": "tsc",
20
+ "bundle:ide": "node scripts/bundle-ide.mjs",
20
21
  "typecheck": "tsc --noEmit",
21
22
  "lint": "eslint src/ tests/",
22
23
  "test": "vitest run",
@@ -51,6 +52,7 @@
51
52
  },
52
53
  "type": "module",
53
54
  "dependencies": {
55
+ "@modelcontextprotocol/sdk": "^1.30.0",
54
56
  "chalk": "^5.6.2",
55
57
  "cli-highlight": "^2.1.11",
56
58
  "eventemitter3": "^5.0.4",
@@ -71,12 +73,12 @@
71
73
  "@types/react": "^19.2.14",
72
74
  "@typescript-eslint/eslint-plugin": "^8.0.0",
73
75
  "@typescript-eslint/parser": "^8.0.0",
74
- "@vitest/coverage-v8": "^3.2.4",
76
+ "@vitest/coverage-v8": "^4.1.11",
75
77
  "eslint": "^9.0.0",
76
78
  "playwright": "^1.59.1",
77
79
  "tsx": "^4.21.0",
78
80
  "typescript": "^6.0.2",
79
- "vitest": "^3.0.0"
81
+ "vitest": "^4.1.11"
80
82
  },
81
83
  "optionalDependencies": {
82
84
  "playwright": "^1.59.1"