termux-dev 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,196 @@
1
+ import fs from 'fs/promises';
2
+ import fsSync from 'fs';
3
+ import path from 'path';
4
+ import os from 'os';
5
+ import pc from 'picocolors';
6
+ import { MCPClient } from './client.js';
7
+ import { getCurrentTheme } from '../cli/theme.js';
8
+ function stripAnsi(str) {
9
+ return str.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');
10
+ }
11
+ export class MCPManager {
12
+ static instance;
13
+ clients = new Map();
14
+ tools = [];
15
+ serverStatuses = new Map();
16
+ isInitialized = false;
17
+ constructor() { }
18
+ static getInstance() {
19
+ if (!MCPManager.instance) {
20
+ MCPManager.instance = new MCPManager();
21
+ }
22
+ return MCPManager.instance;
23
+ }
24
+ async init(explicitConfigs) {
25
+ if (this.isInitialized) {
26
+ return this.tools;
27
+ }
28
+ const configs = explicitConfigs || await this.loadConfigs();
29
+ const serverEntries = Object.entries(configs);
30
+ if (serverEntries.length === 0) {
31
+ this.isInitialized = true;
32
+ return [];
33
+ }
34
+ const initPromises = serverEntries.map(async ([name, cfg]) => {
35
+ if (cfg.disabled) {
36
+ this.serverStatuses.set(name, {
37
+ name,
38
+ command: `${cfg.command} ${(cfg.args || []).join(' ')}`.trim(),
39
+ status: 'disabled',
40
+ toolsCount: 0,
41
+ tools: []
42
+ });
43
+ return;
44
+ }
45
+ this.serverStatuses.set(name, {
46
+ name,
47
+ command: `${cfg.command} ${(cfg.args || []).join(' ')}`.trim(),
48
+ status: 'connecting',
49
+ toolsCount: 0,
50
+ tools: []
51
+ });
52
+ const client = new MCPClient(name, cfg);
53
+ this.clients.set(name, client);
54
+ try {
55
+ const mcpTools = await client.start();
56
+ this.serverStatuses.set(name, {
57
+ name,
58
+ command: `${cfg.command} ${(cfg.args || []).join(' ')}`.trim(),
59
+ status: 'connected',
60
+ toolsCount: mcpTools.length,
61
+ tools: mcpTools.map(t => t.name)
62
+ });
63
+ // Convert MCP tools into devx Tool format
64
+ for (const mt of mcpTools) {
65
+ const namespacedName = `mcp__${name}__${mt.name}`;
66
+ const devxTool = {
67
+ name: namespacedName,
68
+ definition: {
69
+ name: namespacedName,
70
+ description: `[MCP: ${name}] ${mt.description || mt.name}`,
71
+ parameters: {
72
+ type: 'object',
73
+ properties: mt.inputSchema?.properties || {},
74
+ required: mt.inputSchema?.required
75
+ }
76
+ },
77
+ validateArgs(_args) { },
78
+ async execute(args) {
79
+ return await client.callTool(mt.name, args);
80
+ }
81
+ };
82
+ this.tools.push(devxTool);
83
+ }
84
+ }
85
+ catch (err) {
86
+ this.serverStatuses.set(name, {
87
+ name,
88
+ command: `${cfg.command} ${(cfg.args || []).join(' ')}`.trim(),
89
+ status: 'failed',
90
+ toolsCount: 0,
91
+ tools: [],
92
+ error: err.message
93
+ });
94
+ }
95
+ });
96
+ await Promise.all(initPromises);
97
+ this.isInitialized = true;
98
+ return this.tools;
99
+ }
100
+ getTools() {
101
+ return this.tools;
102
+ }
103
+ getStatuses() {
104
+ return Array.from(this.serverStatuses.values());
105
+ }
106
+ async reload() {
107
+ this.stopAll();
108
+ this.isInitialized = false;
109
+ this.clients.clear();
110
+ this.tools = [];
111
+ this.serverStatuses.clear();
112
+ return await this.init();
113
+ }
114
+ stopAll() {
115
+ for (const client of this.clients.values()) {
116
+ try {
117
+ client.close();
118
+ }
119
+ catch { }
120
+ }
121
+ this.clients.clear();
122
+ }
123
+ renderStatusCard() {
124
+ const theme = getCurrentTheme();
125
+ const statuses = this.getStatuses();
126
+ const cols = Math.min(process.stdout.columns || 80, 80);
127
+ const boxWidth = Math.max(48, cols - 4);
128
+ const innerWidth = boxWidth - 6;
129
+ const padRow = (left, right) => {
130
+ const plainLen = stripAnsi(left).length + stripAnsi(right).length;
131
+ const spaces = Math.max(1, innerWidth - plainLen);
132
+ return `│ ${left}${' '.repeat(spaces)}${right} │`;
133
+ };
134
+ const header = theme.colorFn('┌─ ') + pc.bold('🔌 Model Context Protocol (MCP) Servers') + ' ' + theme.colorFn('─'.repeat(Math.max(2, boxWidth - 43)) + '┐');
135
+ const divider = theme.colorFn('├' + '─'.repeat(boxWidth - 2) + '┤');
136
+ const footer = theme.colorFn('└' + '─'.repeat(boxWidth - 2) + '┘');
137
+ const lines = [header];
138
+ if (statuses.length === 0) {
139
+ lines.push(padRow(pc.dim('No MCP servers configured.'), ''));
140
+ lines.push(padRow(pc.dim('Configure in .devx/mcp.json or ~/.devxrc.json'), ''));
141
+ lines.push(footer);
142
+ return lines.join('\n') + '\n';
143
+ }
144
+ for (let i = 0; i < statuses.length; i++) {
145
+ const s = statuses[i];
146
+ if (i > 0)
147
+ lines.push(divider);
148
+ let statusBadge = pc.green('🟢 Connected');
149
+ if (s.status === 'connecting')
150
+ statusBadge = pc.yellow('🟡 Connecting');
151
+ if (s.status === 'failed')
152
+ statusBadge = pc.red('🔴 Failed');
153
+ if (s.status === 'disabled')
154
+ statusBadge = pc.dim('⚪ Disabled');
155
+ lines.push(padRow(pc.bold(pc.white(`Server: ${s.name}`)), statusBadge));
156
+ lines.push(padRow(pc.dim(` Command: ${s.command.slice(0, 36)}${s.command.length > 36 ? '...' : ''}`), pc.cyan(`${s.toolsCount} tools`)));
157
+ if (s.tools.length > 0) {
158
+ const toolsListStr = s.tools.slice(0, 3).map(t => pc.dim(`• ${t}`)).join(' ');
159
+ const extra = s.tools.length > 3 ? pc.dim(` +${s.tools.length - 3} more`) : '';
160
+ lines.push(padRow(` ${toolsListStr}${extra}`, ''));
161
+ }
162
+ if (s.error) {
163
+ lines.push(padRow(pc.red(` Error: ${s.error.slice(0, innerWidth - 10)}`), ''));
164
+ }
165
+ }
166
+ lines.push(footer);
167
+ return lines.join('\n') + '\n';
168
+ }
169
+ async loadConfigs() {
170
+ const result = {};
171
+ const configPaths = [
172
+ path.join(os.homedir(), '.devxrc.json'),
173
+ path.join(process.cwd(), '.devx', 'mcp.json'),
174
+ path.join(process.cwd(), '.claude', 'mcp.json'),
175
+ path.join(process.cwd(), '.devx.json'),
176
+ path.join(process.cwd(), '.mcp.json')
177
+ ];
178
+ for (const pth of configPaths) {
179
+ try {
180
+ if (fsSync.existsSync(pth)) {
181
+ const raw = await fs.readFile(pth, 'utf8');
182
+ const parsed = JSON.parse(raw);
183
+ if (parsed && typeof parsed.mcpServers === 'object') {
184
+ for (const [name, cfg] of Object.entries(parsed.mcpServers)) {
185
+ if (cfg && typeof cfg === 'object' && cfg.command) {
186
+ result[name] = cfg;
187
+ }
188
+ }
189
+ }
190
+ }
191
+ }
192
+ catch { }
193
+ }
194
+ return result;
195
+ }
196
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -23,16 +23,25 @@ function isPathOutsideCwd(targetPath) {
23
23
  function isDangerousBashCommand(commandStr) {
24
24
  if (!commandStr)
25
25
  return false;
26
- const lower = commandStr.toLowerCase().trim();
27
- return (lower.includes('rm -rf /') ||
28
- lower.includes('rm -rf ~') ||
29
- lower.includes('rm -rf *') ||
30
- lower.includes('mkfs') ||
31
- lower.includes('dd if=') ||
32
- lower.includes(':(){ :|:& };:') ||
33
- lower.includes('chmod -r 777 /') ||
34
- lower.includes('> /dev/sda') ||
35
- lower.includes('format c:'));
26
+ // Normalize whitespace: collapse multiple spaces/tabs into single space
27
+ const norm = commandStr.toLowerCase().replace(/\s+/g, ' ').trim();
28
+ // Pattern matching rm with combined flags (-rf, -fr, -r -f, etc.) targeting root, home, termux prefix, or glob
29
+ const isDangerousRm = /rm\s+-(?:[a-z]*r[a-z]*f|[a-z]*f[a-z]*r)\s+(?:\/|\/\*|~|~\/|\*|\$home|\$prefix|\/data\/data\/com\.termux)/i.test(norm) ||
30
+ /rm\s+-[a-z]*r[a-z]*\s+-[a-z]*f[a-z]*\s+(?:\/|\/\*|~|~\/|\*|\$home|\$prefix|\/data\/data\/com\.termux)/i.test(norm) ||
31
+ /rm\s+-[a-z]*f[a-z]*\s+-[a-z]*r[a-z]*\s+(?:\/|\/\*|~|~\/|\*|\$home|\$prefix|\/data\/data\/com\.termux)/i.test(norm);
32
+ return (isDangerousRm ||
33
+ norm.includes('rm -rf /') ||
34
+ norm.includes('rm -rf ~') ||
35
+ norm.includes('rm -rf *') ||
36
+ norm.includes('rm -rf $prefix') ||
37
+ norm.includes('rm -rf $home') ||
38
+ norm.includes('rm -rf /data/data/com.termux') ||
39
+ norm.includes('mkfs') ||
40
+ norm.includes('dd if=') ||
41
+ norm.includes(':(){ :|:& };:') ||
42
+ norm.includes('chmod -r 777 /') ||
43
+ norm.includes('> /dev/sda') ||
44
+ norm.includes('format c:'));
36
45
  }
37
46
  /**
38
47
  * Checks if a command contains chaining, redirection, or subshell operators.
@@ -98,15 +107,30 @@ export class CLIConsoleGuard {
98
107
  return true;
99
108
  }
100
109
  }
110
+ // 5. MCP Tools: ask if autoApprove is false
111
+ if (t.startsWith('mcp__')) {
112
+ return true;
113
+ }
101
114
  return false;
102
115
  }
103
116
  async askUser(toolName, args) {
104
117
  const t = (toolName || '').toLowerCase();
105
118
  const cmd = args?.command || args?.cmd || '';
106
119
  const isDangerous = t === 'bash' && isDangerousBashCommand(cmd);
120
+ // In headless / non-interactive environment without TTY, deny confirmation-requiring actions immediately
121
+ if (!process.stdin.isTTY) {
122
+ console.error(pc.red(`\n🛡️ [PERMISSION DENIED] Action '${toolName}' requires user confirmation in safe mode, but no interactive terminal is available. Pass --yolo (-y) to auto-approve actions in headless mode.`));
123
+ return false;
124
+ }
107
125
  if (isDangerous) {
108
126
  p.log.error(pc.bold(pc.red('⚠️ [SECURITY WARNING] Agent requested a potentially dangerous system command!')));
109
127
  }
128
+ else if (t.startsWith('mcp__')) {
129
+ const parts = toolName.split('__');
130
+ const serverName = parts[1] || 'mcp';
131
+ const mcpToolName = parts.slice(2).join('__');
132
+ p.log.warn(pc.bold(pc.yellow(`🛡️ [PERMISSION GUARD] Agent wants to call MCP Tool: ${pc.cyan(serverName)} / ${pc.green(mcpToolName)}`)));
133
+ }
110
134
  else {
111
135
  p.log.warn(pc.bold(pc.yellow(`🛡️ [PERMISSION GUARD] Agent wants to execute: ${pc.cyan(toolName)}`)));
112
136
  }
@@ -131,11 +131,20 @@ export class OpenAIProvider {
131
131
  }
132
132
  return {
133
133
  content: choice.content || null,
134
- toolCalls: choice.tool_calls ? choice.tool_calls.map((tc) => ({
135
- id: tc.id,
136
- name: tc.function.name,
137
- arguments: JSON.parse(tc.function.arguments)
138
- })) : undefined,
134
+ toolCalls: choice.tool_calls ? choice.tool_calls.map((tc) => {
135
+ let parsedArgs = {};
136
+ try {
137
+ parsedArgs = JSON.parse(tc.function.arguments);
138
+ }
139
+ catch {
140
+ parsedArgs = {};
141
+ }
142
+ return {
143
+ id: tc.id || `call_${Math.random().toString(36).substring(2, 9)}`,
144
+ name: tc.function.name,
145
+ arguments: parsedArgs
146
+ };
147
+ }) : undefined,
139
148
  usage
140
149
  };
141
150
  }
@@ -20,20 +20,27 @@ export const bashTool = {
20
20
  return new Promise((resolve, reject) => {
21
21
  const proc = spawn(args.command, { shell: true });
22
22
  let output = '';
23
+ let isTruncated = false;
23
24
  const timeout = setTimeout(() => {
24
25
  proc.kill();
25
26
  resolve(output + '\n[Process killed due to timeout]');
26
27
  }, 30000);
27
28
  proc.stdout.on('data', (data) => {
29
+ if (isTruncated)
30
+ return;
28
31
  output += data.toString();
29
32
  if (output.length > 20000) {
33
+ isTruncated = true;
30
34
  output = output.substring(0, 20000) + '\n[Output truncated]';
31
35
  proc.kill();
32
36
  }
33
37
  });
34
38
  proc.stderr.on('data', (data) => {
39
+ if (isTruncated)
40
+ return;
35
41
  output += data.toString();
36
42
  if (output.length > 20000) {
43
+ isTruncated = true;
37
44
  output = output.substring(0, 20000) + '\n[Output truncated]';
38
45
  proc.kill();
39
46
  }
package/dist/tools/fs.js CHANGED
@@ -153,7 +153,7 @@ export const editFileTool = {
153
153
  let addCounter = startLine;
154
154
  addedArr.forEach((l) => diffLines.push(`${addCounter++} + ${l}`));
155
155
  contextAfter.forEach((l) => diffLines.push(`${addCounter++} ${l}`));
156
- const newContent = content.replace(target, args.replacement);
156
+ const newContent = content.slice(0, targetIndex) + args.replacement + content.slice(targetIndex + target.length);
157
157
  await fs.writeFile(args.path, newContent, 'utf8');
158
158
  return JSON.stringify({
159
159
  status: 'success',
@@ -9,11 +9,13 @@ import { saveMemoryTool } from '../core/memory.js';
9
9
  import { planReadyTool, lastPlanReady, resetPlanReady } from './plan.js';
10
10
  import { todoListTool, currentTodoList, resetTodoList } from './todo.js';
11
11
  import { servePreviewTool } from './server.js';
12
+ import { MCPManager } from '../mcp/manager.js';
12
13
  export function getTools(planMode) {
13
14
  const baseTools = [readFileTool, listDirTool, searchTool, askQuestionsTool, webSearchTool, fetchUrlTool, saveMemoryTool, planReadyTool, todoListTool];
15
+ const mcpTools = MCPManager.getInstance().getTools();
14
16
  if (planMode) {
15
- return baseTools;
17
+ return [...baseTools, ...mcpTools];
16
18
  }
17
- return [...baseTools, writeFileTool, editFileTool, mkdirTool, bashTool, diagnoseCodeTool, installPackageTool, servePreviewTool];
19
+ return [...baseTools, writeFileTool, editFileTool, mkdirTool, bashTool, diagnoseCodeTool, installPackageTool, servePreviewTool, ...mcpTools];
18
20
  }
19
21
  export { webSearchTool, fetchUrlTool, diagnoseCodeTool, installPackageTool, saveMemoryTool, planReadyTool, lastPlanReady, resetPlanReady, todoListTool, currentTodoList, resetTodoList, servePreviewTool };
package/dist/tools/web.js CHANGED
@@ -1,8 +1,8 @@
1
1
  function stripHtml(html) {
2
2
  return html
3
- .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
4
- .replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '')
5
- .replace(/<svg\b[^<]*(?:(?!<\/svg>)<[^<]*)*<\/svg>/gi, '')
3
+ .replace(/<script\b[\s\S]*?<\/script>/gi, '')
4
+ .replace(/<style\b[\s\S]*?<\/style>/gi, '')
5
+ .replace(/<svg\b[\s\S]*?<\/svg>/gi, '')
6
6
  .replace(/<[^>]+>/g, ' ')
7
7
  .replace(/&quot;/g, '"')
8
8
  .replace(/&amp;/g, '&')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "termux-dev",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "Ultra-fast, terminal-native AI coding assistant and agent built for Android Termux, Windows, macOS, and Linux.",
5
5
  "main": "dist/cli/index.js",
6
6
  "type": "module",