termux-dev 1.3.0 → 1.4.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 +2 -0
- package/assets/banner.svg +1 -1
- package/assets/preview.png +0 -0
- package/dist/cli/doctor.js +8 -2
- package/dist/cli/headless.js +1 -1
- package/dist/cli/index.js +214 -188
- package/dist/cli/prompt.js +1 -0
- package/dist/cli/server.js +1 -1
- package/dist/cli/updater.js +0 -6
- package/dist/core/commands.js +3 -3
- package/dist/core/history.js +10 -0
- package/dist/core/loop.js +5 -1
- package/dist/core/models.js +1 -1
- package/dist/core/pricing.js +1 -1
- package/dist/core/usage.js +21 -21
- package/dist/mcp/client.js +218 -0
- package/dist/mcp/manager.js +196 -0
- package/dist/mcp/types.js +1 -0
- package/dist/permissions/guard.js +34 -10
- package/dist/providers/openai.js +14 -5
- package/dist/tools/bash.js +7 -0
- package/dist/tools/fs.js +1 -1
- package/dist/tools/index.js +4 -2
- package/dist/tools/web.js +3 -3
- package/package.json +1 -1
package/dist/core/pricing.js
CHANGED
|
@@ -42,7 +42,7 @@ export function getModelPricing(modelName) {
|
|
|
42
42
|
return cache[clean];
|
|
43
43
|
if (cache[short])
|
|
44
44
|
return cache[short];
|
|
45
|
-
const baseName = short.replace(
|
|
45
|
+
const baseName = short.replace(/-\d{4,8}$/, '').replace(/:latest$/, '');
|
|
46
46
|
if (cache[baseName])
|
|
47
47
|
return cache[baseName];
|
|
48
48
|
if (clean.includes('gpt-4o-mini'))
|
package/dist/core/usage.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import pc from 'picocolors';
|
|
2
2
|
import { getCurrentTheme } from '../cli/theme.js';
|
|
3
|
+
function stripAnsi(str) {
|
|
4
|
+
return str.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');
|
|
5
|
+
}
|
|
3
6
|
export class UsageTracker {
|
|
4
7
|
static instance;
|
|
5
|
-
requestsCount = 0;
|
|
6
8
|
bytesSent = 0;
|
|
7
9
|
bytesReceived = 0;
|
|
10
|
+
requestsCount = 0;
|
|
8
11
|
promptTokens = 0;
|
|
9
12
|
completionTokens = 0;
|
|
10
13
|
totalCost = 0;
|
|
@@ -20,24 +23,24 @@ export class UsageTracker {
|
|
|
20
23
|
setLimit(limitMB) {
|
|
21
24
|
this.dataSaverLimitMB = limitMB;
|
|
22
25
|
}
|
|
23
|
-
recordRequest(
|
|
24
|
-
this.
|
|
25
|
-
this.
|
|
26
|
+
recordRequest(payloadBytes) {
|
|
27
|
+
this.bytesSent += payloadBytes;
|
|
28
|
+
this.requestsCount += 1;
|
|
26
29
|
}
|
|
27
|
-
recordResponseChunk(
|
|
28
|
-
this.bytesReceived +=
|
|
30
|
+
recordResponseChunk(chunkBytes) {
|
|
31
|
+
this.bytesReceived += chunkBytes;
|
|
29
32
|
}
|
|
30
|
-
recordTokens(
|
|
31
|
-
this.promptTokens +=
|
|
32
|
-
this.completionTokens +=
|
|
33
|
-
this.totalCost +=
|
|
33
|
+
recordTokens(promptTokens, completionTokens, cost) {
|
|
34
|
+
this.promptTokens += promptTokens;
|
|
35
|
+
this.completionTokens += completionTokens;
|
|
36
|
+
this.totalCost += cost;
|
|
34
37
|
}
|
|
35
38
|
getSummary() {
|
|
36
39
|
return {
|
|
37
|
-
requestsCount: this.requestsCount,
|
|
38
40
|
bytesSent: this.bytesSent,
|
|
39
41
|
bytesReceived: this.bytesReceived,
|
|
40
42
|
totalBytes: this.bytesSent + this.bytesReceived,
|
|
43
|
+
requestsCount: this.requestsCount,
|
|
41
44
|
promptTokens: this.promptTokens,
|
|
42
45
|
completionTokens: this.completionTokens,
|
|
43
46
|
totalTokens: this.promptTokens + this.completionTokens,
|
|
@@ -46,19 +49,15 @@ export class UsageTracker {
|
|
|
46
49
|
};
|
|
47
50
|
}
|
|
48
51
|
static formatBytes(bytes) {
|
|
49
|
-
if (bytes <= 0)
|
|
50
|
-
return '0 B';
|
|
51
52
|
if (bytes < 1024)
|
|
52
53
|
return `${bytes} B`;
|
|
53
54
|
if (bytes < 1024 * 1024)
|
|
54
55
|
return `${(bytes / 1024).toFixed(1)} KB`;
|
|
55
|
-
|
|
56
|
-
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
|
57
|
-
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
|
56
|
+
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
|
58
57
|
}
|
|
59
58
|
static formatTokens(n) {
|
|
60
|
-
if (n >=
|
|
61
|
-
return `${(n /
|
|
59
|
+
if (n >= 1000000)
|
|
60
|
+
return `${(n / 1000000).toFixed(2)}M`;
|
|
62
61
|
if (n >= 1000)
|
|
63
62
|
return `${(n / 1000).toFixed(1)}k`;
|
|
64
63
|
return `${n}`;
|
|
@@ -67,10 +66,11 @@ export class UsageTracker {
|
|
|
67
66
|
const theme = getCurrentTheme();
|
|
68
67
|
const summary = this.getSummary();
|
|
69
68
|
const cols = Math.min(process.stdout.columns || 80, 75);
|
|
70
|
-
const boxWidth = Math.max(
|
|
71
|
-
const innerWidth = boxWidth -
|
|
69
|
+
const boxWidth = Math.max(38, cols - 4);
|
|
70
|
+
const innerWidth = boxWidth - 6;
|
|
72
71
|
const padRow = (label, value) => {
|
|
73
|
-
const
|
|
72
|
+
const visibleValLen = stripAnsi(value).length;
|
|
73
|
+
const plainLen = label.length + visibleValLen;
|
|
74
74
|
const spaces = Math.max(1, innerWidth - plainLen);
|
|
75
75
|
return `│ ${pc.bold(label)}${' '.repeat(spaces)}${value} │`;
|
|
76
76
|
};
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { spawn } from 'child_process';
|
|
2
|
+
export class MCPClient {
|
|
3
|
+
name;
|
|
4
|
+
config;
|
|
5
|
+
process = null;
|
|
6
|
+
nextRequestId = 1;
|
|
7
|
+
pendingRequests = new Map();
|
|
8
|
+
buffer = '';
|
|
9
|
+
tools = [];
|
|
10
|
+
isConnected = false;
|
|
11
|
+
constructor(name, config) {
|
|
12
|
+
this.name = name;
|
|
13
|
+
this.config = config;
|
|
14
|
+
}
|
|
15
|
+
async start() {
|
|
16
|
+
if (this.config.disabled) {
|
|
17
|
+
throw new Error(`MCP server "${this.name}" is disabled in configuration.`);
|
|
18
|
+
}
|
|
19
|
+
return new Promise(async (resolve, reject) => {
|
|
20
|
+
let isSettled = false;
|
|
21
|
+
const initialTimer = setTimeout(() => {
|
|
22
|
+
if (!isSettled) {
|
|
23
|
+
isSettled = true;
|
|
24
|
+
this.close();
|
|
25
|
+
reject(new Error(`MCP server "${this.name}" initialization timed out after 15s.`));
|
|
26
|
+
}
|
|
27
|
+
}, 15000);
|
|
28
|
+
try {
|
|
29
|
+
const env = {
|
|
30
|
+
...process.env,
|
|
31
|
+
...(this.config.env || {})
|
|
32
|
+
};
|
|
33
|
+
const isWindows = process.platform === 'win32';
|
|
34
|
+
const useShell = isWindows && (this.config.command.endsWith('.cmd') ||
|
|
35
|
+
this.config.command.endsWith('.bat') ||
|
|
36
|
+
this.config.command === 'npx' ||
|
|
37
|
+
this.config.command === 'npm');
|
|
38
|
+
this.process = spawn(this.config.command, this.config.args || [], {
|
|
39
|
+
env,
|
|
40
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
41
|
+
shell: useShell
|
|
42
|
+
});
|
|
43
|
+
this.process.stdout?.on('data', (data) => {
|
|
44
|
+
this.handleStdout(data.toString());
|
|
45
|
+
});
|
|
46
|
+
this.process.stderr?.on('data', (_data) => {
|
|
47
|
+
// Stderr from MCP servers is used for logging/debugging
|
|
48
|
+
});
|
|
49
|
+
this.process.on('error', (err) => {
|
|
50
|
+
if (!isSettled) {
|
|
51
|
+
isSettled = true;
|
|
52
|
+
clearTimeout(initialTimer);
|
|
53
|
+
reject(new Error(`Failed to start MCP server "${this.name}": ${err.message}`));
|
|
54
|
+
}
|
|
55
|
+
this.cleanup();
|
|
56
|
+
});
|
|
57
|
+
this.process.on('close', (_code) => {
|
|
58
|
+
this.cleanup();
|
|
59
|
+
});
|
|
60
|
+
// 1. Initialize Handshake
|
|
61
|
+
const initResult = await this.sendRequest('initialize', {
|
|
62
|
+
protocolVersion: '2024-11-05',
|
|
63
|
+
capabilities: {},
|
|
64
|
+
clientInfo: {
|
|
65
|
+
name: 'devx',
|
|
66
|
+
version: '1.4.0'
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
if (!initResult) {
|
|
70
|
+
throw new Error(`Invalid initialize response from MCP server "${this.name}".`);
|
|
71
|
+
}
|
|
72
|
+
// 2. Send initialized notification
|
|
73
|
+
this.sendNotification('notifications/initialized', {});
|
|
74
|
+
// 3. Fetch Tools List
|
|
75
|
+
const toolsResult = await this.sendRequest('tools/list', {});
|
|
76
|
+
this.tools = toolsResult?.tools || [];
|
|
77
|
+
this.isConnected = true;
|
|
78
|
+
if (!isSettled) {
|
|
79
|
+
isSettled = true;
|
|
80
|
+
clearTimeout(initialTimer);
|
|
81
|
+
resolve(this.tools);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
catch (err) {
|
|
85
|
+
if (!isSettled) {
|
|
86
|
+
isSettled = true;
|
|
87
|
+
clearTimeout(initialTimer);
|
|
88
|
+
this.close();
|
|
89
|
+
reject(err);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
getTools() {
|
|
95
|
+
return this.tools;
|
|
96
|
+
}
|
|
97
|
+
hasConnected() {
|
|
98
|
+
return this.isConnected;
|
|
99
|
+
}
|
|
100
|
+
async callTool(toolName, args) {
|
|
101
|
+
if (!this.process || !this.isConnected) {
|
|
102
|
+
throw new Error(`MCP server "${this.name}" is not connected.`);
|
|
103
|
+
}
|
|
104
|
+
const res = await this.sendRequest('tools/call', {
|
|
105
|
+
name: toolName,
|
|
106
|
+
arguments: args || {}
|
|
107
|
+
}, 60000); // 60s timeout for tool calls
|
|
108
|
+
if (!res || !res.content) {
|
|
109
|
+
return JSON.stringify(res || {});
|
|
110
|
+
}
|
|
111
|
+
const outputParts = [];
|
|
112
|
+
for (const c of res.content) {
|
|
113
|
+
if (c.type === 'text' && c.text) {
|
|
114
|
+
outputParts.push(c.text);
|
|
115
|
+
}
|
|
116
|
+
else if (c.type === 'image' && c.data) {
|
|
117
|
+
outputParts.push(`[Image content (${c.mimeType || 'image/png'})]`);
|
|
118
|
+
}
|
|
119
|
+
else if (c.type === 'resource') {
|
|
120
|
+
outputParts.push(`[Resource: ${JSON.stringify(c)}]`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const finalResult = outputParts.join('\n\n') || JSON.stringify(res);
|
|
124
|
+
if (res.isError) {
|
|
125
|
+
throw new Error(finalResult);
|
|
126
|
+
}
|
|
127
|
+
return finalResult;
|
|
128
|
+
}
|
|
129
|
+
handleStdout(chunk) {
|
|
130
|
+
this.buffer += chunk;
|
|
131
|
+
const lines = this.buffer.split('\n');
|
|
132
|
+
this.buffer = lines.pop() || '';
|
|
133
|
+
for (const line of lines) {
|
|
134
|
+
const trimmed = line.trim();
|
|
135
|
+
if (!trimmed)
|
|
136
|
+
continue;
|
|
137
|
+
try {
|
|
138
|
+
const msg = JSON.parse(trimmed);
|
|
139
|
+
if ('id' in msg && msg.id !== undefined) {
|
|
140
|
+
const pending = this.pendingRequests.get(msg.id);
|
|
141
|
+
if (pending) {
|
|
142
|
+
clearTimeout(pending.timer);
|
|
143
|
+
this.pendingRequests.delete(msg.id);
|
|
144
|
+
if (msg.error) {
|
|
145
|
+
pending.reject(new Error(`MCP error ${msg.error.code}: ${msg.error.message}`));
|
|
146
|
+
}
|
|
147
|
+
else {
|
|
148
|
+
pending.resolve(msg.result);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
// Ignore non-JSON line outputs (e.g. startup banner)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
sendRequest(method, params, timeoutMs = 15000) {
|
|
159
|
+
return new Promise((resolve, reject) => {
|
|
160
|
+
if (!this.process || !this.process.stdin) {
|
|
161
|
+
return reject(new Error(`MCP server "${this.name}" process is not running.`));
|
|
162
|
+
}
|
|
163
|
+
const id = this.nextRequestId++;
|
|
164
|
+
const timer = setTimeout(() => {
|
|
165
|
+
if (this.pendingRequests.has(id)) {
|
|
166
|
+
this.pendingRequests.delete(id);
|
|
167
|
+
reject(new Error(`MCP request "${method}" to server "${this.name}" timed out (${timeoutMs / 1000}s).`));
|
|
168
|
+
}
|
|
169
|
+
}, timeoutMs);
|
|
170
|
+
this.pendingRequests.set(id, { resolve, reject, timer });
|
|
171
|
+
const request = {
|
|
172
|
+
jsonrpc: '2.0',
|
|
173
|
+
id,
|
|
174
|
+
method,
|
|
175
|
+
params
|
|
176
|
+
};
|
|
177
|
+
try {
|
|
178
|
+
this.process.stdin.write(JSON.stringify(request) + '\n');
|
|
179
|
+
}
|
|
180
|
+
catch (err) {
|
|
181
|
+
clearTimeout(timer);
|
|
182
|
+
this.pendingRequests.delete(id);
|
|
183
|
+
reject(new Error(`Failed to write to MCP server "${this.name}": ${err.message}`));
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
sendNotification(method, params) {
|
|
188
|
+
if (!this.process || !this.process.stdin)
|
|
189
|
+
return;
|
|
190
|
+
const notif = {
|
|
191
|
+
jsonrpc: '2.0',
|
|
192
|
+
method,
|
|
193
|
+
params
|
|
194
|
+
};
|
|
195
|
+
try {
|
|
196
|
+
this.process.stdin.write(JSON.stringify(notif) + '\n');
|
|
197
|
+
}
|
|
198
|
+
catch { }
|
|
199
|
+
}
|
|
200
|
+
close() {
|
|
201
|
+
this.cleanup();
|
|
202
|
+
if (this.process) {
|
|
203
|
+
try {
|
|
204
|
+
this.process.kill();
|
|
205
|
+
}
|
|
206
|
+
catch { }
|
|
207
|
+
this.process = null;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
cleanup() {
|
|
211
|
+
this.isConnected = false;
|
|
212
|
+
for (const [id, req] of this.pendingRequests.entries()) {
|
|
213
|
+
clearTimeout(req.timer);
|
|
214
|
+
req.reject(new Error(`MCP server "${this.name}" disconnected.`));
|
|
215
|
+
}
|
|
216
|
+
this.pendingRequests.clear();
|
|
217
|
+
}
|
|
218
|
+
}
|
|
@@ -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
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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
|
}
|
package/dist/providers/openai.js
CHANGED
|
@@ -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
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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
|
}
|
package/dist/tools/bash.js
CHANGED
|
@@ -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.
|
|
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',
|
package/dist/tools/index.js
CHANGED
|
@@ -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[
|
|
4
|
-
.replace(/<style\b[
|
|
5
|
-
.replace(/<svg\b[
|
|
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(/"/g, '"')
|
|
8
8
|
.replace(/&/g, '&')
|