@tensorspark/dravix-code 0.0.0-stage → 1.5.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/cli/commands.js +127 -0
- package/dist/cli/index.js +321 -0
- package/dist/cli/repl.js +3433 -0
- package/dist/services/ai.js +296 -0
- package/dist/services/auth.js +67 -0
- package/dist/services/context.js +260 -0
- package/dist/services/conversations.js +79 -0
- package/dist/services/executor.js +944 -0
- package/dist/services/undo.js +181 -0
- package/dist/services/usage.js +60 -0
- package/dist/utils/display.js +265 -0
- package/dist/utils/fileops.js +17 -0
- package/dist/utils/layout.js +82 -0
- package/package.json +38 -4
- package/README.md +0 -3
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
const AI_PROXY = 'https://dravix.app/ai-proxy.php';
|
|
2
|
+
const PROMPT_URL = 'https://dravix.app/cli-prompt.php';
|
|
3
|
+
export const FLASH_MODEL = 'deepseek-v4-pro'; // fast, cheap — default for all tasks
|
|
4
|
+
export const PRO_MODEL = 'deepseek-v4-pro'; // high-reasoning — used after errors/retries
|
|
5
|
+
export const CLAUDE_MODEL = 'anthropic/claude-sonnet-4'; // high-quality — for complex tasks
|
|
6
|
+
// Model routing: decide which model to use based on task complexity
|
|
7
|
+
export function selectModel(userMessage, retryCount = 0) {
|
|
8
|
+
// Always use PRO_MODEL for retries (better at fixing errors)
|
|
9
|
+
if (retryCount > 0)
|
|
10
|
+
return PRO_MODEL;
|
|
11
|
+
const msg = userMessage.toLowerCase();
|
|
12
|
+
// Complex task indicators
|
|
13
|
+
const COMPLEX_INDICATORS = [
|
|
14
|
+
'refactor', 'architecture', 'complex', 'redesign', 'migrate',
|
|
15
|
+
'debug', 'fix error', 'error handling', 'optimization', 'performance',
|
|
16
|
+
'security', 'authentication', 'database', 'deploy', 'infrastructure',
|
|
17
|
+
'test', 'testing', 'integration', 'api', 'microservice',
|
|
18
|
+
'typescript', 'type safety', 'interface', 'generic',
|
|
19
|
+
];
|
|
20
|
+
// Long messages are usually more complex
|
|
21
|
+
if (userMessage.length > 500)
|
|
22
|
+
return PRO_MODEL;
|
|
23
|
+
// Check for complex indicators
|
|
24
|
+
for (const indicator of COMPLEX_INDICATORS) {
|
|
25
|
+
if (msg.includes(indicator))
|
|
26
|
+
return PRO_MODEL;
|
|
27
|
+
}
|
|
28
|
+
// Multi-file tasks (mentions multiple files)
|
|
29
|
+
const fileMentions = (userMessage.match(/\.\w{2,5}/g) ?? []).length;
|
|
30
|
+
if (fileMentions > 5)
|
|
31
|
+
return PRO_MODEL;
|
|
32
|
+
// Default: use flash for speed
|
|
33
|
+
return FLASH_MODEL;
|
|
34
|
+
}
|
|
35
|
+
export async function fetchSystemPrompt(token) {
|
|
36
|
+
try {
|
|
37
|
+
const res = await fetch(`${PROMPT_URL}?token=${encodeURIComponent(token)}`, {
|
|
38
|
+
signal: AbortSignal.timeout(10000),
|
|
39
|
+
});
|
|
40
|
+
if (!res.ok)
|
|
41
|
+
return { prompt: '', webDesignerSkill: '', isCreator: false };
|
|
42
|
+
const data = await res.json();
|
|
43
|
+
return {
|
|
44
|
+
prompt: data.prompt ?? '',
|
|
45
|
+
webDesignerSkill: data.web_designer_skill ?? '',
|
|
46
|
+
isCreator: data.is_creator ?? false,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return { prompt: '', webDesignerSkill: '', isCreator: false };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const TIMEOUT_MS = 300_000; // 5 min — AI may generate large responses
|
|
54
|
+
const CHUNK_TIMEOUT_MS = 60_000; // 1 min without any chunk = abort
|
|
55
|
+
const MAX_CONTINUATIONS = 5; // auto-continue up to 5 times on length cutoff
|
|
56
|
+
const MAX_429_RETRIES = 3; // retry on rate-limit with exponential backoff
|
|
57
|
+
// Smart context management: priority-based trimming with summarization
|
|
58
|
+
function prepareMessages(messages) {
|
|
59
|
+
const MAX_CHARS = 150_000; // ~45k tokens
|
|
60
|
+
const MIN_KEEP = 6; // Always keep at least last 6 messages (3 user + 3 assistant)
|
|
61
|
+
let totalChars = messages.reduce((s, m) => s + String(m.content).length, 0);
|
|
62
|
+
// If under limit, just convert and return
|
|
63
|
+
if (totalChars <= MAX_CHARS) {
|
|
64
|
+
return convertAndMerge(messages);
|
|
65
|
+
}
|
|
66
|
+
// Smart trimming strategy:
|
|
67
|
+
// 1. Keep system prompt (index 0)
|
|
68
|
+
// 2. Keep last MIN_KEEP messages
|
|
69
|
+
// 3. Summarize middle messages
|
|
70
|
+
// 4. Drop oldest middle messages if still over limit
|
|
71
|
+
const systemMsg = messages[0];
|
|
72
|
+
const recentMessages = messages.slice(-MIN_KEEP);
|
|
73
|
+
const middleMessages = messages.slice(1, messages.length - MIN_KEEP);
|
|
74
|
+
// Calculate chars for system + recent
|
|
75
|
+
const systemChars = String(systemMsg.content).length;
|
|
76
|
+
const recentChars = recentMessages.reduce((s, m) => s + String(m.content).length, 0);
|
|
77
|
+
const availableForMiddle = MAX_CHARS - systemChars - recentChars;
|
|
78
|
+
if (availableForMiddle <= 0 || middleMessages.length === 0) {
|
|
79
|
+
// No room for middle messages — just use system + recent
|
|
80
|
+
return convertAndMerge([systemMsg, ...recentMessages]);
|
|
81
|
+
}
|
|
82
|
+
// Summarize middle messages into a compact summary
|
|
83
|
+
const summary = summarizeMessages(middleMessages, availableForMiddle);
|
|
84
|
+
const summarizedMessages = [
|
|
85
|
+
systemMsg,
|
|
86
|
+
{ role: 'system', content: `[Previous conversation summary]\n${summary}` },
|
|
87
|
+
...recentMessages,
|
|
88
|
+
];
|
|
89
|
+
return convertAndMerge(summarizedMessages);
|
|
90
|
+
}
|
|
91
|
+
// Summarize messages into a compact format
|
|
92
|
+
function summarizeMessages(messages, maxChars) {
|
|
93
|
+
const parts = [];
|
|
94
|
+
let totalChars = 0;
|
|
95
|
+
for (const msg of messages) {
|
|
96
|
+
const content = String(msg.content);
|
|
97
|
+
const role = msg.role === 'user' ? 'User' : 'AI';
|
|
98
|
+
// For short messages, include them fully
|
|
99
|
+
if (content.length < 200) {
|
|
100
|
+
const line = `${role}: ${content.slice(0, 200)}`;
|
|
101
|
+
if (totalChars + line.length < maxChars) {
|
|
102
|
+
parts.push(line);
|
|
103
|
+
totalChars += line.length;
|
|
104
|
+
}
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
// For long messages, include first 100 chars + "... [truncated]"
|
|
108
|
+
const truncated = `${role}: ${content.slice(0, 100)}... [${content.length} chars total]`;
|
|
109
|
+
if (totalChars + truncated.length < maxChars) {
|
|
110
|
+
parts.push(truncated);
|
|
111
|
+
totalChars += truncated.length;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return parts.join('\n') || '[No previous context available]';
|
|
115
|
+
}
|
|
116
|
+
// Convert messages to OpenAI format and merge consecutive user messages
|
|
117
|
+
function convertAndMerge(messages) {
|
|
118
|
+
const converted = messages.map((msg, i) => {
|
|
119
|
+
if (msg.role === 'system' && i > 0)
|
|
120
|
+
return { role: 'user', content: msg.content };
|
|
121
|
+
return msg;
|
|
122
|
+
});
|
|
123
|
+
const merged = [];
|
|
124
|
+
for (const msg of converted) {
|
|
125
|
+
const last = merged[merged.length - 1];
|
|
126
|
+
if (last && last.role === 'user' && msg.role === 'user') {
|
|
127
|
+
last.content = last.content + '\n\n' + msg.content;
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
merged.push({ ...msg });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return merged;
|
|
134
|
+
}
|
|
135
|
+
async function doSingleRequest(messages, token, abort, onChunk, model = FLASH_MODEL) {
|
|
136
|
+
const requestTimer = setTimeout(() => abort.abort(), TIMEOUT_MS);
|
|
137
|
+
const attemptFetch = async (attempt) => {
|
|
138
|
+
const res = await fetch(AI_PROXY, {
|
|
139
|
+
method: 'POST',
|
|
140
|
+
signal: abort.signal,
|
|
141
|
+
headers: {
|
|
142
|
+
'Content-Type': 'application/json',
|
|
143
|
+
'X-CLI-Token': token,
|
|
144
|
+
'X-CLI-Version': '1.1.5',
|
|
145
|
+
},
|
|
146
|
+
body: JSON.stringify({
|
|
147
|
+
provider: 'deepseek',
|
|
148
|
+
model,
|
|
149
|
+
messages: prepareMessages(messages),
|
|
150
|
+
stream: true,
|
|
151
|
+
temperature: 0.1,
|
|
152
|
+
max_tokens: 40000,
|
|
153
|
+
}),
|
|
154
|
+
});
|
|
155
|
+
// Retry on rate-limit with exponential backoff (2s, 4s, 8s)
|
|
156
|
+
if (res.status === 429 && attempt < MAX_429_RETRIES - 1) {
|
|
157
|
+
await new Promise(r => setTimeout(r, 2000 * Math.pow(2, attempt)));
|
|
158
|
+
return attemptFetch(attempt + 1);
|
|
159
|
+
}
|
|
160
|
+
return res;
|
|
161
|
+
};
|
|
162
|
+
try {
|
|
163
|
+
const res = await attemptFetch(0);
|
|
164
|
+
if (!res.ok || !res.body) {
|
|
165
|
+
const text = await res.text().catch(() => '');
|
|
166
|
+
let msg = `HTTP ${res.status}`;
|
|
167
|
+
try {
|
|
168
|
+
msg = JSON.parse(text).error ?? msg;
|
|
169
|
+
}
|
|
170
|
+
catch { }
|
|
171
|
+
throw new Error(msg);
|
|
172
|
+
}
|
|
173
|
+
const reader = res.body.getReader();
|
|
174
|
+
const decoder = new TextDecoder();
|
|
175
|
+
let buffer = '';
|
|
176
|
+
let finishReason = 'stop';
|
|
177
|
+
let chunkResponse = '';
|
|
178
|
+
outer: while (true) {
|
|
179
|
+
let chunkTimer = setTimeout(() => abort.abort(), CHUNK_TIMEOUT_MS);
|
|
180
|
+
const { done, value } = await reader.read().finally(() => {
|
|
181
|
+
if (chunkTimer) {
|
|
182
|
+
clearTimeout(chunkTimer);
|
|
183
|
+
chunkTimer = null;
|
|
184
|
+
}
|
|
185
|
+
});
|
|
186
|
+
if (done)
|
|
187
|
+
break;
|
|
188
|
+
buffer += decoder.decode(value, { stream: true });
|
|
189
|
+
const lines = buffer.split('\n');
|
|
190
|
+
buffer = lines.pop() ?? '';
|
|
191
|
+
for (const line of lines) {
|
|
192
|
+
if (!line.startsWith('data: '))
|
|
193
|
+
continue;
|
|
194
|
+
const data = line.slice(6).trim();
|
|
195
|
+
if (data === '[DONE]')
|
|
196
|
+
break outer;
|
|
197
|
+
let json;
|
|
198
|
+
try {
|
|
199
|
+
json = JSON.parse(data);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
// Detect API/proxy error events in the SSE stream — was previously silently ignored
|
|
205
|
+
if (json.error) {
|
|
206
|
+
const e = json.error;
|
|
207
|
+
const msg = typeof e.message === 'string' ? e.message
|
|
208
|
+
: typeof json.error === 'string' ? json.error
|
|
209
|
+
: JSON.stringify(json.error);
|
|
210
|
+
throw new Error(msg);
|
|
211
|
+
}
|
|
212
|
+
const choices = json.choices;
|
|
213
|
+
const delta = choices?.[0]?.delta;
|
|
214
|
+
const text = (delta?.content ?? '');
|
|
215
|
+
const rawFr = (choices?.[0]?.finish_reason ?? '');
|
|
216
|
+
if (rawFr && rawFr !== 'null')
|
|
217
|
+
finishReason = rawFr;
|
|
218
|
+
if (text) {
|
|
219
|
+
chunkResponse += text;
|
|
220
|
+
onChunk(text);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
// Detect non-SSE JSON error body (e.g. proxy returns plain JSON error instead of SSE)
|
|
225
|
+
if (!chunkResponse) {
|
|
226
|
+
if (buffer.trim()) {
|
|
227
|
+
try {
|
|
228
|
+
const errData = JSON.parse(buffer.trim());
|
|
229
|
+
if (errData.error) {
|
|
230
|
+
const e = errData.error;
|
|
231
|
+
const msg = typeof e.message === 'string' ? e.message
|
|
232
|
+
: typeof errData.error === 'string' ? errData.error
|
|
233
|
+
: JSON.stringify(errData.error);
|
|
234
|
+
throw new Error(msg);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
catch (pe) {
|
|
238
|
+
if (!(pe instanceof SyntaxError))
|
|
239
|
+
throw pe;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (!finishReason || finishReason === 'stop') {
|
|
243
|
+
throw new Error('No response from AI — check your connection or try again');
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return { finishReason, response: chunkResponse };
|
|
247
|
+
}
|
|
248
|
+
finally {
|
|
249
|
+
clearTimeout(requestTimer);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
export async function streamChat(messages, token, onChunk, onDone, onError, cancelSignal, model = FLASH_MODEL) {
|
|
253
|
+
const abort = new AbortController();
|
|
254
|
+
const forwardCancel = () => abort.abort();
|
|
255
|
+
cancelSignal?.addEventListener('abort', forwardCancel);
|
|
256
|
+
try {
|
|
257
|
+
let currentMessages = [...messages];
|
|
258
|
+
for (let attempt = 0; attempt <= MAX_CONTINUATIONS; attempt++) {
|
|
259
|
+
if (cancelSignal?.aborted) {
|
|
260
|
+
onDone();
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
const { finishReason, response } = await doSingleRequest(currentMessages, token, abort, onChunk, model);
|
|
264
|
+
if (finishReason === 'length' && attempt < MAX_CONTINUATIONS) {
|
|
265
|
+
// Token limit hit — auto-continue seamlessly, no visible break to user
|
|
266
|
+
const tail = response.slice(-400);
|
|
267
|
+
// Detect if cut off inside an open tag — need to complete it first
|
|
268
|
+
const openTagMatch = response.match(/<(write_file|edit_file|run_command|read_file|search_code)[^>]*>(?:(?!<\/\1>)[\s\S])*$/);
|
|
269
|
+
const contPrompt = openTagMatch
|
|
270
|
+
? `Your previous response was cut off inside a <${openTagMatch[1]}> tag. The tail was:\n"...${tail}"\nFirst COMPLETE the current tag (close it properly), then continue with any remaining work. Output ONLY the raw continuation — no intro, no preamble.`
|
|
271
|
+
: `Your previous response was cut off. It ended with:\n"...${tail}"\nContinue from that exact point — complete any remaining file edits or tasks. Output ONLY the raw continuation — no intro, no preamble, no repeated text.`;
|
|
272
|
+
currentMessages = [
|
|
273
|
+
...currentMessages,
|
|
274
|
+
{ role: 'assistant', content: response },
|
|
275
|
+
{ role: 'user', content: contPrompt },
|
|
276
|
+
];
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
onDone();
|
|
282
|
+
}
|
|
283
|
+
catch (err) {
|
|
284
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
285
|
+
if (e.name === 'AbortError' && cancelSignal?.aborted) {
|
|
286
|
+
onDone(); // user-initiated cancel → clean stop with partial response
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
const msg = e.name === 'AbortError' ? 'Request timed out — check your connection.' : e.message;
|
|
290
|
+
onError(new Error(msg));
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
finally {
|
|
294
|
+
cancelSignal?.removeEventListener('abort', forwardCancel);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import * as os from 'os';
|
|
4
|
+
const CONFIG_DIR = path.join(os.homedir(), '.dravix-code');
|
|
5
|
+
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
|
|
6
|
+
const AUTH_URL = 'https://dravix.app/cli-auth.php';
|
|
7
|
+
const VERIFY_URL = 'https://dravix.app/cli-auth.php?action=verify&token=';
|
|
8
|
+
function readConfig() {
|
|
9
|
+
try {
|
|
10
|
+
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8'));
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return {};
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function writeConfig(config) {
|
|
17
|
+
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
|
18
|
+
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf-8');
|
|
19
|
+
}
|
|
20
|
+
export function saveConfig(config) {
|
|
21
|
+
writeConfig(config);
|
|
22
|
+
}
|
|
23
|
+
export function getToken() {
|
|
24
|
+
return readConfig().token ?? null;
|
|
25
|
+
}
|
|
26
|
+
export function getSavedUser() {
|
|
27
|
+
const c = readConfig();
|
|
28
|
+
return { name: c.name, email: c.email };
|
|
29
|
+
}
|
|
30
|
+
export function isLoggedIn() {
|
|
31
|
+
return !!getToken();
|
|
32
|
+
}
|
|
33
|
+
export function logout() {
|
|
34
|
+
const config = readConfig();
|
|
35
|
+
delete config.token;
|
|
36
|
+
delete config.name;
|
|
37
|
+
delete config.email;
|
|
38
|
+
writeConfig(config);
|
|
39
|
+
}
|
|
40
|
+
export async function verifyAndSave(token) {
|
|
41
|
+
try {
|
|
42
|
+
const res = await fetch(VERIFY_URL + encodeURIComponent(token));
|
|
43
|
+
const data = await res.json();
|
|
44
|
+
if (!data.valid)
|
|
45
|
+
return null;
|
|
46
|
+
writeConfig({ token, name: data.name ?? '', email: data.email ?? '' });
|
|
47
|
+
return { name: data.name ?? '', email: data.email ?? '' };
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export async function checkPlan(email) {
|
|
54
|
+
try {
|
|
55
|
+
const res = await fetch('https://dravix.app/check_user_plus.php', {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
headers: { 'Content-Type': 'application/json' },
|
|
58
|
+
body: JSON.stringify({ email }),
|
|
59
|
+
});
|
|
60
|
+
const data = await res.json();
|
|
61
|
+
return data.isPlus ? 'Plus' : 'Free';
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return 'Free';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export { AUTH_URL };
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import * as fs from 'fs';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { execSync } from 'child_process';
|
|
4
|
+
const IGNORE = new Set([
|
|
5
|
+
'node_modules', '.git', 'dist', 'build', '.next', 'out',
|
|
6
|
+
'__pycache__', '.cache', 'coverage', '.turbo', 'vendor',
|
|
7
|
+
'.tox', '.eggs', '.venv', 'venv', 'env', '.env',
|
|
8
|
+
]);
|
|
9
|
+
const CODE_EXTS = new Set([
|
|
10
|
+
'.ts', '.tsx', '.js', '.jsx', '.py', '.html', '.css', '.scss',
|
|
11
|
+
'.json', '.md', '.txt', '.sh', '.php', '.sql', '.yaml', '.yml',
|
|
12
|
+
'.java', '.go', '.rs', '.c', '.cpp', '.h', '.vue', '.svelte',
|
|
13
|
+
'.env', '.env.example', '.env.local',
|
|
14
|
+
]);
|
|
15
|
+
const CONFIG_FILES = new Set([
|
|
16
|
+
'package.json', 'tsconfig.json', 'vite.config.ts', 'vite.config.js',
|
|
17
|
+
'next.config.js', 'next.config.ts', 'nuxt.config.ts', 'nuxt.config.js',
|
|
18
|
+
'composer.json', 'requirements.txt', 'pyproject.toml', 'Cargo.toml',
|
|
19
|
+
'go.mod', 'pom.xml', 'build.gradle', 'Dockerfile', 'docker-compose.yml',
|
|
20
|
+
'.env', '.env.example', '.eslintrc.js', '.prettierrc',
|
|
21
|
+
'tailwind.config.js', 'tailwind.config.ts', 'postcss.config.js',
|
|
22
|
+
'webpack.config.js', 'rollup.config.js', 'babel.config.js',
|
|
23
|
+
'.gitignore', 'README.md',
|
|
24
|
+
]);
|
|
25
|
+
export function getProjectFiles(root, maxFiles = 50) {
|
|
26
|
+
const files = [];
|
|
27
|
+
function walk(dir, depth = 0) {
|
|
28
|
+
if (depth > 4 || files.length >= maxFiles)
|
|
29
|
+
return;
|
|
30
|
+
let entries;
|
|
31
|
+
try {
|
|
32
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
// Sort: config files first, then directories, then files
|
|
38
|
+
const sorted = entries.sort((a, b) => {
|
|
39
|
+
const aConfig = CONFIG_FILES.has(a.name) ? 0 : 1;
|
|
40
|
+
const bConfig = CONFIG_FILES.has(b.name) ? 0 : 1;
|
|
41
|
+
if (aConfig !== bConfig)
|
|
42
|
+
return aConfig - bConfig;
|
|
43
|
+
if (a.isDirectory() !== b.isDirectory())
|
|
44
|
+
return a.isDirectory() ? -1 : 1;
|
|
45
|
+
return a.name.localeCompare(b.name);
|
|
46
|
+
});
|
|
47
|
+
for (const e of sorted) {
|
|
48
|
+
if (IGNORE.has(e.name) || e.name.startsWith('.'))
|
|
49
|
+
continue;
|
|
50
|
+
const fullPath = path.join(dir, e.name);
|
|
51
|
+
if (e.isDirectory()) {
|
|
52
|
+
walk(fullPath, depth + 1);
|
|
53
|
+
}
|
|
54
|
+
else if (CODE_EXTS.has(path.extname(e.name).toLowerCase()) || CONFIG_FILES.has(e.name)) {
|
|
55
|
+
files.push(path.relative(root, fullPath));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
walk(root);
|
|
60
|
+
return files;
|
|
61
|
+
}
|
|
62
|
+
export function readFileContent(filePath, maxLen = 8000) {
|
|
63
|
+
try {
|
|
64
|
+
const content = fs.readFileSync(filePath, 'utf-8');
|
|
65
|
+
if (content.length > maxLen)
|
|
66
|
+
return content.slice(0, maxLen) + '\n... (truncated)';
|
|
67
|
+
return content;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return '';
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export function getGitStatus(root) {
|
|
74
|
+
try {
|
|
75
|
+
return execSync('git status --short', {
|
|
76
|
+
cwd: root,
|
|
77
|
+
encoding: 'utf-8',
|
|
78
|
+
timeout: 5000,
|
|
79
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
80
|
+
}).trim();
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return '';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export function getGitBranch(root) {
|
|
87
|
+
try {
|
|
88
|
+
return execSync('git branch --show-current', {
|
|
89
|
+
cwd: root,
|
|
90
|
+
encoding: 'utf-8',
|
|
91
|
+
timeout: 5000,
|
|
92
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
93
|
+
}).trim();
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return '';
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const STOP_WORDS = new Set([
|
|
100
|
+
'this', 'that', 'with', 'from', 'have', 'will', 'what', 'when', 'where', 'make', 'into',
|
|
101
|
+
'does', 'should', 'would', 'could', 'then', 'they', 'your', 'just', 'also', 'more',
|
|
102
|
+
// Tajik/Farsi common words
|
|
103
|
+
'дустам', 'хамин', 'барои', 'метавонед', 'кунед', 'мекунад', 'мешавад', 'аст',
|
|
104
|
+
'ман', 'хам', 'хамон', 'дар', 'ва', 'ки', 'ба', 'аз', 'он', 'буд', 'мебошад', 'кун',
|
|
105
|
+
]);
|
|
106
|
+
/**
|
|
107
|
+
* Extract only the relevant sections of a large file based on user message keywords.
|
|
108
|
+
* Returns numbered lines with context around each match.
|
|
109
|
+
*/
|
|
110
|
+
export function extractRelevantSections(fileContent, userMessage, contextLines = 35) {
|
|
111
|
+
const lines = fileContent.split('\n');
|
|
112
|
+
const total = lines.length;
|
|
113
|
+
// Extract latin technical keywords (CSS classes, HTML tags, JS identifiers)
|
|
114
|
+
const keywords = [...new Set(userMessage
|
|
115
|
+
.toLowerCase()
|
|
116
|
+
.split(/[\s.,!?;:()\[\]{}'"`\/\\]+/)
|
|
117
|
+
.filter(w => w.length >= 3 && !STOP_WORDS.has(w) && /^[\w\-]+$/.test(w)))];
|
|
118
|
+
if (keywords.length === 0) {
|
|
119
|
+
// No latin keywords — return structural preview
|
|
120
|
+
const preview = lines.slice(0, 80).map((l, i) => `${String(i + 1).padStart(4)} │ ${l}`).join('\n');
|
|
121
|
+
return `[File: ${total} lines — no specific keywords found. First 80 lines shown.]\n${preview}\n[Use <read_file lines="N-M"/> to read any other section]`;
|
|
122
|
+
}
|
|
123
|
+
// Find lines matching any keyword
|
|
124
|
+
const included = new Set();
|
|
125
|
+
for (let i = 0; i < lines.length; i++) {
|
|
126
|
+
const low = lines[i].toLowerCase();
|
|
127
|
+
if (keywords.some(kw => low.includes(kw))) {
|
|
128
|
+
const from = Math.max(0, i - contextLines);
|
|
129
|
+
const to = Math.min(total - 1, i + contextLines);
|
|
130
|
+
for (let c = from; c <= to; c++)
|
|
131
|
+
included.add(c);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
if (included.size === 0) {
|
|
135
|
+
const preview = lines.slice(0, 80).map((l, i) => `${String(i + 1).padStart(4)} │ ${l}`).join('\n');
|
|
136
|
+
return `[File: ${total} lines — keywords [${keywords.slice(0, 5).join(', ')}] not found. First 80 lines shown.]\n${preview}\n[Use <search_code> to find specific text]`;
|
|
137
|
+
}
|
|
138
|
+
const sorted = [...included].sort((a, b) => a - b);
|
|
139
|
+
const out = [
|
|
140
|
+
`[File: ${total} lines — showing ${included.size} relevant lines for: ${keywords.slice(0, 6).join(', ')}]`,
|
|
141
|
+
`[⚠ In <find>: copy ONLY the text AFTER " │ " — never include line numbers]`,
|
|
142
|
+
];
|
|
143
|
+
let prev = -2;
|
|
144
|
+
for (const idx of sorted) {
|
|
145
|
+
if (idx > prev + 1)
|
|
146
|
+
out.push(' ···');
|
|
147
|
+
out.push(`${String(idx + 1).padStart(4)} │ ${lines[idx]}`);
|
|
148
|
+
prev = idx;
|
|
149
|
+
}
|
|
150
|
+
out.push(`[Use <read_file lines="N-M"/> to read any section not shown above]`);
|
|
151
|
+
return out.join('\n');
|
|
152
|
+
}
|
|
153
|
+
// Detect top-level subdirectories that look like separate standalone projects
|
|
154
|
+
function detectSeparateProjects(root, files) {
|
|
155
|
+
const topDirFiles = new Map();
|
|
156
|
+
for (const f of files) {
|
|
157
|
+
const slash = f.indexOf('/');
|
|
158
|
+
if (slash === -1)
|
|
159
|
+
continue;
|
|
160
|
+
const dir = f.slice(0, slash);
|
|
161
|
+
if (!topDirFiles.has(dir))
|
|
162
|
+
topDirFiles.set(dir, []);
|
|
163
|
+
topDirFiles.get(dir).push(path.basename(f).toLowerCase());
|
|
164
|
+
}
|
|
165
|
+
const PROJECT_FILES = new Set([
|
|
166
|
+
'package.json', 'composer.json', 'config.php', 'index.php', 'index.js',
|
|
167
|
+
'index.ts', 'main.py', 'app.py', 'bot.php', 'main.go', 'pom.xml',
|
|
168
|
+
'requirements.txt', 'pyproject.toml', 'Cargo.toml', 'go.mod',
|
|
169
|
+
]);
|
|
170
|
+
const projectDirs = [];
|
|
171
|
+
for (const [dir, dirFiles] of topDirFiles) {
|
|
172
|
+
if (dirFiles.some(f => PROJECT_FILES.has(f)))
|
|
173
|
+
projectDirs.push(dir);
|
|
174
|
+
}
|
|
175
|
+
return projectDirs;
|
|
176
|
+
}
|
|
177
|
+
// Detect project type from files
|
|
178
|
+
function detectProjectType(files) {
|
|
179
|
+
const fileNames = files.map(f => path.basename(f).toLowerCase());
|
|
180
|
+
const fileExts = files.map(f => path.extname(f).toLowerCase());
|
|
181
|
+
if (fileNames.includes('package.json')) {
|
|
182
|
+
if (fileNames.includes('next.config.js') || fileNames.includes('next.config.ts'))
|
|
183
|
+
return 'Next.js';
|
|
184
|
+
if (fileNames.includes('nuxt.config.ts') || fileNames.includes('nuxt.config.js'))
|
|
185
|
+
return 'Nuxt.js';
|
|
186
|
+
if (fileNames.includes('vite.config.ts') || fileNames.includes('vite.config.js'))
|
|
187
|
+
return 'Vite';
|
|
188
|
+
if (fileNames.includes('angular.json'))
|
|
189
|
+
return 'Angular';
|
|
190
|
+
if (fileNames.includes('vue.config.js'))
|
|
191
|
+
return 'Vue.js';
|
|
192
|
+
if (fileExts.includes('.tsx') || fileExts.includes('.jsx'))
|
|
193
|
+
return 'React';
|
|
194
|
+
return 'Node.js';
|
|
195
|
+
}
|
|
196
|
+
if (fileNames.includes('composer.json'))
|
|
197
|
+
return 'Laravel/PHP';
|
|
198
|
+
if (fileNames.includes('requirements.txt') || fileNames.includes('pyproject.toml')) {
|
|
199
|
+
if (fileNames.includes('manage.py'))
|
|
200
|
+
return 'Django';
|
|
201
|
+
if (fileNames.includes('app.py') || fileNames.includes('flask'))
|
|
202
|
+
return 'Flask';
|
|
203
|
+
return 'Python';
|
|
204
|
+
}
|
|
205
|
+
if (fileNames.includes('go.mod'))
|
|
206
|
+
return 'Go';
|
|
207
|
+
if (fileNames.includes('Cargo.toml'))
|
|
208
|
+
return 'Rust';
|
|
209
|
+
if (fileNames.includes('pom.xml') || fileNames.includes('build.gradle'))
|
|
210
|
+
return 'Java';
|
|
211
|
+
if (fileExts.includes('.vue'))
|
|
212
|
+
return 'Vue.js';
|
|
213
|
+
if (fileExts.includes('.svelte'))
|
|
214
|
+
return 'Svelte';
|
|
215
|
+
return 'Unknown';
|
|
216
|
+
}
|
|
217
|
+
export function buildContext(root) {
|
|
218
|
+
const files = getProjectFiles(root);
|
|
219
|
+
const git = getGitStatus(root);
|
|
220
|
+
const branch = getGitBranch(root);
|
|
221
|
+
const projectName = path.basename(root);
|
|
222
|
+
const shell = process.platform === 'win32' ? 'Windows — PowerShell'
|
|
223
|
+
: process.platform === 'darwin' ? 'macOS — bash/zsh'
|
|
224
|
+
: 'Linux — bash';
|
|
225
|
+
const separateProjects = detectSeparateProjects(root, files);
|
|
226
|
+
const parentDirWarning = separateProjects.length >= 2
|
|
227
|
+
? `\n⚠ PARENT DIRECTORY — contains ${separateProjects.length} separate projects: ${separateProjects.join(', ')}\n` +
|
|
228
|
+
`RULE: NEVER modify files inside existing project folders (${separateProjects.join(', ')}) unless the user explicitly asks to work on that specific project.\n` +
|
|
229
|
+
`When creating a NEW project, ALWAYS create a NEW dedicated subfolder.`
|
|
230
|
+
: '';
|
|
231
|
+
const projectType = detectProjectType(files);
|
|
232
|
+
// Auto-read key config files for better context
|
|
233
|
+
const configContents = [];
|
|
234
|
+
const configToRead = ['package.json', 'tsconfig.json', 'composer.json', 'requirements.txt'];
|
|
235
|
+
for (const cfg of configToRead) {
|
|
236
|
+
const cfgPath = path.join(root, cfg);
|
|
237
|
+
if (fs.existsSync(cfgPath)) {
|
|
238
|
+
try {
|
|
239
|
+
const content = fs.readFileSync(cfgPath, 'utf-8');
|
|
240
|
+
if (content.length < 3000) {
|
|
241
|
+
configContents.push(`[${cfg}]:\n${content}`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
catch { }
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const gitInfo = branch ? `Branch: ${branch}\nGit status:\n${git || '(clean)'}` : `Git status:\n${git || '(clean)'}`;
|
|
248
|
+
let context = `Project: ${projectName}
|
|
249
|
+
Type: ${projectType}
|
|
250
|
+
Working dir: ${root}
|
|
251
|
+
OS: ${shell}
|
|
252
|
+
${gitInfo}
|
|
253
|
+
Files:
|
|
254
|
+
${files.length > 0 ? files.join('\n') : '(empty project)'}`;
|
|
255
|
+
if (configContents.length > 0) {
|
|
256
|
+
context += `\n\nKey config files:\n${configContents.join('\n\n')}`;
|
|
257
|
+
}
|
|
258
|
+
context += parentDirWarning;
|
|
259
|
+
return context;
|
|
260
|
+
}
|