@markmayandi/bridge 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1519 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Complete DeepSeek-Harness Powered Secure MCP Server
5
+ *
6
+ * 100% Complete Implementation of DeepSeek Harness (dsh) Core Tools:
7
+ * - Subprocess Shell Execution (dsh-tool-bash, dsh-tool-pwsh)
8
+ * - Background Job Management (dsh-tool-jobs, dsh-jobs-local)
9
+ * - Git Tracking, Diffs & Status (dsh-base, dsh-tool-worktree)
10
+ * - Workspace Dependency Analyzer (dsh-tool-workspace-dependencies)
11
+ * - Web Documentation Fetcher (dsh-tool-web)
12
+ * - Atomic Write & Revert History (dsh-atomic-write, dsh-tool-str-replace-editor)
13
+ * - Plan & Goal Checklist Mode (dsh-plan-mode, dsh-tool-goal, dsh-tool-todo)
14
+ * - Sandboxed Filesystem Suite (dsh-tool-fs)
15
+ * - Dynamic Project Selection & Strict Folder Jailing
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const readline = require('readline');
21
+ const http = require('http');
22
+ const { exec, spawn, execSync } = require('child_process');
23
+
24
+ // ==========================================
25
+ // 1. State & CLI Parsing
26
+ // ==========================================
27
+
28
+ const args = process.argv.slice(2);
29
+
30
+ let rootDir = null;
31
+ let isReadOnly = false;
32
+ let allowEnvFiles = false;
33
+ let httpPort = null;
34
+ let currentPlan = []; // dsh-plan-mode
35
+ const fileBackups = new Map(); // dsh-atomic-write: path -> [previous_contents]
36
+ const backgroundJobs = new Map(); // dsh-tool-jobs: jobId -> { proc, cmd, startTime, logs }
37
+ let nextJobId = 1;
38
+
39
+ for (let i = 0; i < args.length; i++) {
40
+ const arg = args[i];
41
+ if (arg === '--read-only') {
42
+ isReadOnly = true;
43
+ } else if (arg === '--allow-env') {
44
+ allowEnvFiles = true;
45
+ } else if (arg === '--http') {
46
+ httpPort = parseInt(args[++i], 10) || 3000;
47
+ } else if (!arg.startsWith('-') && !rootDir) {
48
+ rootDir = arg;
49
+ }
50
+ }
51
+
52
+ if (!rootDir) {
53
+ rootDir = process.cwd();
54
+ }
55
+
56
+ try {
57
+ rootDir = fs.realpathSync(path.resolve(rootDir));
58
+ } catch (e) {
59
+ rootDir = process.cwd();
60
+ }
61
+
62
+ const IGNORED_DIRS = new Set([
63
+ 'node_modules', '.git', '.svn', '.hg', '.vscode', '.idea',
64
+ 'dist', 'build', 'out', 'target', '.next', '.nuxt',
65
+ 'coverage', '.venv', 'venv', '__pycache__', '.pytest_cache'
66
+ ]);
67
+
68
+ const SENSITIVE_PATTERNS = [
69
+ /^\.env($|\..+)/i,
70
+ /\.pem$/i,
71
+ /\.key$/i,
72
+ /^id_rsa/i,
73
+ /^id_ed25519/i,
74
+ /credentials\.json$/i
75
+ ];
76
+
77
+ const BLOCKED_COMMANDS = [
78
+ /\bformat\b/i,
79
+ /\brm\s+(-rf?|--recursive)\s+[\/\\]/i,
80
+ /\bdel\s+\/[sfq]\s+[c-z]:\\/i,
81
+ /\bshutdown\b/i,
82
+ /\bmkfs\b/i,
83
+ /\bdd\s+if=/i,
84
+ /\bfdisk\b/i
85
+ ];
86
+
87
+ function logInfo(msg) {
88
+ process.stderr.write(`[DSH-MCP] ${msg}\n`);
89
+ }
90
+
91
+ // ==========================================
92
+ // 2. Security Sandbox Validation
93
+ // ==========================================
94
+
95
+ function validateAndResolve(requestedPath, allowNonExistent = false) {
96
+ if (!requestedPath || typeof requestedPath !== 'string') {
97
+ throw new Error('Path parameter must be a non-empty string.');
98
+ }
99
+
100
+ if (requestedPath.includes('\0')) {
101
+ throw new Error('Security Violation: Null byte detected.');
102
+ }
103
+
104
+ const resolved = path.resolve(rootDir, requestedPath);
105
+ const rel = path.relative(rootDir, resolved);
106
+
107
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
108
+ throw new Error(`Security Violation: Path "${requestedPath}" escapes the sandboxed project folder (${rootDir}).`);
109
+ }
110
+
111
+ const baseName = path.basename(resolved);
112
+ if (!allowEnvFiles) {
113
+ for (const pat of SENSITIVE_PATTERNS) {
114
+ if (pat.test(baseName)) {
115
+ throw new Error(`Security Violation: Access to sensitive file "${baseName}" is blocked by security policy.`);
116
+ }
117
+ }
118
+ }
119
+
120
+ if (fs.existsSync(resolved)) {
121
+ try {
122
+ const real = fs.realpathSync(resolved);
123
+ const realRel = path.relative(rootDir, real);
124
+ if (realRel.startsWith('..') || path.isAbsolute(realRel)) {
125
+ throw new Error(`Security Violation: Symlink points outside allowed directory (${real}).`);
126
+ }
127
+ } catch (e) {
128
+ if (e.message.includes('Security Violation')) throw e;
129
+ }
130
+ } else if (!allowNonExistent) {
131
+ throw new Error(`File or directory does not exist: "${requestedPath}"`);
132
+ }
133
+
134
+ return resolved;
135
+ }
136
+
137
+ function isBinaryFile(filePath) {
138
+ const binaryExtensions = new Set([
139
+ '.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico',
140
+ '.pdf', '.zip', '.tar', '.gz', '.7z', '.rar',
141
+ '.exe', '.dll', '.so', '.dylib', '.bin',
142
+ '.woff', '.woff2', '.ttf', '.mp3', '.mp4'
143
+ ]);
144
+ const ext = path.extname(filePath).toLowerCase();
145
+ if (binaryExtensions.has(ext)) return true;
146
+
147
+ try {
148
+ const fd = fs.openSync(filePath, 'r');
149
+ const buffer = Buffer.alloc(1024);
150
+ const bytesRead = fs.readSync(fd, buffer, 0, 1024, 0);
151
+ fs.closeSync(fd);
152
+ for (let i = 0; i < bytesRead; i++) {
153
+ if (buffer[i] === 0) return true;
154
+ }
155
+ } catch (e) {}
156
+ return false;
157
+ }
158
+
159
+ function openWindowsFolderPicker() {
160
+ const psScript = `
161
+ Add-Type -AssemblyName System.Windows.Forms
162
+ $d = New-Object System.Windows.Forms.FolderBrowserDialog
163
+ $d.Description = "Select the Project Folder to Sandbox for the LLM:"
164
+ $d.ShowNewFolderButton = $true
165
+ if ($d.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
166
+ Write-Output $d.SelectedPath
167
+ }
168
+ `.replace(/\r?\n/g, ' ');
169
+
170
+ try {
171
+ const output = execSync(`powershell -NoProfile -NonInteractive -Command "${psScript}"`, {
172
+ encoding: 'utf-8',
173
+ stdio: ['ignore', 'pipe', 'ignore']
174
+ }).trim();
175
+ return output || null;
176
+ } catch (e) {
177
+ return null;
178
+ }
179
+ }
180
+
181
+ // ==========================================
182
+ // 3. Complete DeepSeek Harness Tool Definitions
183
+ // ==========================================
184
+
185
+ const tools = [
186
+ // --- 1. Subprocess Execution (dsh-tool-bash, dsh-tool-pwsh) ---
187
+ {
188
+ name: 'bash',
189
+ description: 'DeepSeek Harness Bash: Runs a command in Bash/Shell inside the project directory.',
190
+ inputSchema: {
191
+ type: 'object',
192
+ properties: {
193
+ command: {
194
+ type: 'string',
195
+ description: 'The command to execute.'
196
+ },
197
+ timeout_seconds: {
198
+ type: 'number',
199
+ description: 'Timeout in seconds.'
200
+ }
201
+ },
202
+ required: ['command']
203
+ }
204
+ },
205
+ {
206
+ name: 'pwsh',
207
+ description: 'DeepSeek Harness PowerShell: Runs a PowerShell command inside the project directory.',
208
+ inputSchema: {
209
+ type: 'object',
210
+ properties: {
211
+ command: {
212
+ type: 'string',
213
+ description: 'The PowerShell command to execute.'
214
+ },
215
+ timeout_seconds: {
216
+ type: 'number',
217
+ description: 'Timeout in seconds.'
218
+ }
219
+ },
220
+ required: ['command']
221
+ }
222
+ },
223
+ {
224
+ name: 'execute_command',
225
+ description: 'DeepSeek Harness Shell: Executes a terminal command (pytest, npm test, python script.py, etc.) strictly inside the project root directory. Captures exit code, stdout, and stderr for testing and verification.',
226
+ inputSchema: {
227
+ type: 'object',
228
+ properties: {
229
+ command: {
230
+ type: 'string',
231
+ description: 'The shell command to execute inside the project directory.'
232
+ },
233
+ timeout_seconds: {
234
+ type: 'number',
235
+ description: 'Maximum runtime in seconds (default: 30, max: 60).',
236
+ default: 30
237
+ }
238
+ },
239
+ required: ['command']
240
+ }
241
+ },
242
+
243
+ // --- 2. Background Jobs (dsh-tool-jobs, dsh-jobs-local) ---
244
+ {
245
+ name: 'jobs',
246
+ description: 'DeepSeek Harness Background Jobs: Manage long-running background tasks (start, status, logs, stop, list).',
247
+ inputSchema: {
248
+ type: 'object',
249
+ properties: {
250
+ action: {
251
+ type: 'string',
252
+ enum: ['start', 'status', 'logs', 'stop', 'list'],
253
+ description: 'Action to perform.'
254
+ },
255
+ command: {
256
+ type: 'string',
257
+ description: 'Command to run when action="start".'
258
+ },
259
+ job_id: {
260
+ type: 'number',
261
+ description: 'Job ID for status, logs, or stop.'
262
+ }
263
+ },
264
+ required: ['action']
265
+ }
266
+ },
267
+ {
268
+ name: 'manage_background_job',
269
+ description: 'DeepSeek Background Job Runner: Starts long-running processes (e.g., "npm run dev", local servers, file watchers), checks their logs, or stops them.',
270
+ inputSchema: {
271
+ type: 'object',
272
+ properties: {
273
+ action: {
274
+ type: 'string',
275
+ enum: ['start', 'status', 'logs', 'stop', 'list'],
276
+ description: 'Job action to perform.'
277
+ },
278
+ command: {
279
+ type: 'string',
280
+ description: 'Command to run in background when action="start".'
281
+ },
282
+ job_id: {
283
+ type: 'number',
284
+ description: 'Job ID for status, logs, or stop actions.'
285
+ }
286
+ },
287
+ required: ['action']
288
+ }
289
+ },
290
+
291
+ // --- 3. Git Tracking & Diffs (dsh-base, dsh-tool-worktree) ---
292
+ {
293
+ name: 'git_diff',
294
+ description: 'Inspects uncommitted changes in the repository (git diff). Allows reviewing exact modifications.',
295
+ inputSchema: {
296
+ type: 'object',
297
+ properties: {
298
+ file_path: {
299
+ type: 'string',
300
+ description: 'Optional file path relative to root to inspect diff for.'
301
+ }
302
+ }
303
+ }
304
+ },
305
+ {
306
+ name: 'git_status',
307
+ description: 'Returns the current git status (modified, staged, and untracked files).',
308
+ inputSchema: {
309
+ type: 'object',
310
+ properties: {}
311
+ }
312
+ },
313
+
314
+ // --- 4. Workspace Dependencies (dsh-tool-workspace-dependencies) ---
315
+ {
316
+ name: 'inspect_dependencies',
317
+ description: 'DeepSeek Dependency Analyzer: Inspects project manifests (package.json, requirements.txt, pyproject.toml, Cargo.toml, go.mod, pom.xml) to identify the project tech stack, frameworks, and installed libraries.',
318
+ inputSchema: {
319
+ type: 'object',
320
+ properties: {}
321
+ }
322
+ },
323
+
324
+ // --- 5. Atomic Edit & Revert (dsh-atomic-write, dsh-tool-str-replace-editor) ---
325
+ {
326
+ name: 'edit',
327
+ description: 'DeepSeek Harness Edit: Atomically updates a specific code snippet inside an existing file.',
328
+ inputSchema: {
329
+ type: 'object',
330
+ properties: {
331
+ file_path: {
332
+ type: 'string',
333
+ description: 'Path of the file relative to project root.'
334
+ },
335
+ old_string: {
336
+ type: 'string',
337
+ description: 'Exact code snippet to replace.'
338
+ },
339
+ new_string: {
340
+ type: 'string',
341
+ description: 'New code snippet.'
342
+ },
343
+ replace_all: {
344
+ type: 'boolean',
345
+ description: 'Whether to replace all occurrences (default: false).'
346
+ }
347
+ },
348
+ required: ['file_path', 'old_string', 'new_string']
349
+ }
350
+ },
351
+ {
352
+ name: 'read',
353
+ description: 'DeepSeek Harness Read: Reads a UTF-8 text file and returns line-numbered content.',
354
+ inputSchema: {
355
+ type: 'object',
356
+ properties: {
357
+ file_path: {
358
+ type: 'string',
359
+ description: 'Path of the file relative to project root.'
360
+ },
361
+ offset: {
362
+ type: 'number',
363
+ description: '1-based line number to start reading from (default: 1).'
364
+ },
365
+ limit: {
366
+ type: 'number',
367
+ description: 'Number of lines to read.'
368
+ }
369
+ },
370
+ required: ['file_path']
371
+ }
372
+ },
373
+ {
374
+ name: 'write',
375
+ description: 'DeepSeek Harness Write: Creates or overwrites a file inside the project directory.',
376
+ inputSchema: {
377
+ type: 'object',
378
+ properties: {
379
+ file_path: {
380
+ type: 'string',
381
+ description: 'Path of the file relative to project root.'
382
+ },
383
+ content: {
384
+ type: 'string',
385
+ description: 'Full text content to write.'
386
+ }
387
+ },
388
+ required: ['file_path', 'content']
389
+ }
390
+ },
391
+ {
392
+ name: 'str_replace_editor',
393
+ description: 'DeepSeek Harness Standalone Editor: View, create, replace string, or insert lines into files.',
394
+ inputSchema: {
395
+ type: 'object',
396
+ properties: {
397
+ command: {
398
+ type: 'string',
399
+ enum: ['view', 'create', 'str_replace', 'insert'],
400
+ description: 'Action to perform.'
401
+ },
402
+ path: {
403
+ type: 'string',
404
+ description: 'Path of the file.'
405
+ },
406
+ old_str: {
407
+ type: 'string',
408
+ description: 'Existing string for str_replace.'
409
+ },
410
+ new_str: {
411
+ type: 'string',
412
+ description: 'New string for str_replace or insert.'
413
+ },
414
+ file_text: {
415
+ type: 'string',
416
+ description: 'Content for create.'
417
+ },
418
+ insert_line: {
419
+ type: 'number',
420
+ description: '0-based line number for insert.'
421
+ },
422
+ view_range: {
423
+ type: 'array',
424
+ items: { type: 'number' },
425
+ description: 'Optional [start_line, end_line] for view.'
426
+ }
427
+ },
428
+ required: ['command', 'path']
429
+ }
430
+ },
431
+ {
432
+ name: 'edit_file',
433
+ description: 'DeepSeek Surgical Editor: Atomically replaces a specific text snippet inside an existing file. Automatically creates an undo snapshot before modifying.',
434
+ inputSchema: {
435
+ type: 'object',
436
+ properties: {
437
+ path: {
438
+ type: 'string',
439
+ description: 'Path of the file relative to the project root.'
440
+ },
441
+ target: {
442
+ type: 'string',
443
+ description: 'Exact existing code snippet to replace (must match whitespace exactly).'
444
+ },
445
+ replacement: {
446
+ type: 'string',
447
+ description: 'New code snippet to replace the target with.'
448
+ }
449
+ },
450
+ required: ['path', 'target', 'replacement']
451
+ }
452
+ },
453
+ {
454
+ name: 'revert_file',
455
+ description: 'DeepSeek Atomic Undo: Reverts a file to its previous state prior to the last edit or write operation.',
456
+ inputSchema: {
457
+ type: 'object',
458
+ properties: {
459
+ path: {
460
+ type: 'string',
461
+ description: 'Path of the file to revert relative to the project root.'
462
+ }
463
+ },
464
+ required: ['path']
465
+ }
466
+ },
467
+
468
+ // --- 6. Web Documentation Fetcher (dsh-tool-web) ---
469
+ {
470
+ name: 'fetch_web_documentation',
471
+ description: 'DeepSeek Web Fetcher: Retrieves external documentation or library API references from an HTTPS URL.',
472
+ inputSchema: {
473
+ type: 'object',
474
+ properties: {
475
+ url: {
476
+ type: 'string',
477
+ description: 'The HTTPS URL of the documentation or webpage to retrieve.'
478
+ }
479
+ },
480
+ required: ['url']
481
+ }
482
+ },
483
+
484
+ // --- 7. Plan & Goal Mode (dsh-plan-mode, dsh-tool-goal, dsh-tool-todo) ---
485
+ {
486
+ name: 'plan_mode',
487
+ description: 'DeepSeek Harness Plan Mode: Collaborative milestone planning and checklist tracking (get, set, complete_step).',
488
+ inputSchema: {
489
+ type: 'object',
490
+ properties: {
491
+ action: {
492
+ type: 'string',
493
+ enum: ['get', 'set', 'complete_step'],
494
+ description: 'Action: "get" to view plan, "set" to update plan items, "complete_step" to check off a milestone.'
495
+ },
496
+ plan_items: {
497
+ type: 'array',
498
+ items: { type: 'string' },
499
+ description: 'List of milestones/steps when action is "set".'
500
+ },
501
+ step_index: {
502
+ type: 'number',
503
+ description: '1-based index of the step to mark completed when action is "complete_step".'
504
+ }
505
+ },
506
+ required: ['action']
507
+ }
508
+ },
509
+ {
510
+ name: 'manage_plan',
511
+ description: 'DeepSeek Plan Mode: Creates or updates a living checklist of milestones and goals for the current task.',
512
+ inputSchema: {
513
+ type: 'object',
514
+ properties: {
515
+ action: {
516
+ type: 'string',
517
+ enum: ['get', 'set', 'complete_step'],
518
+ description: 'Action: "get" to view plan, "set" to update plan items, "complete_step" to check off a milestone.'
519
+ },
520
+ plan_items: {
521
+ type: 'array',
522
+ items: { type: 'string' },
523
+ description: 'List of milestones/steps when action is "set".'
524
+ },
525
+ step_index: {
526
+ type: 'number',
527
+ description: '1-based index of the step to mark completed when action is "complete_step".'
528
+ }
529
+ },
530
+ required: ['action']
531
+ }
532
+ },
533
+
534
+ // --- 8. Core Filesystem Suite (dsh-tool-fs) ---
535
+ {
536
+ name: 'select_project_folder',
537
+ description: 'Selects or changes the active sandboxed project folder. Can open a native Windows folder picker dialog or accept a direct path.',
538
+ inputSchema: {
539
+ type: 'object',
540
+ properties: {
541
+ folder_path: {
542
+ type: 'string',
543
+ description: 'Absolute path to project directory, or "browse" to open folder dialog.'
544
+ }
545
+ }
546
+ }
547
+ },
548
+ {
549
+ name: 'get_current_project',
550
+ description: 'Returns information about the currently active project folder, detected dependencies, and sandbox boundaries.',
551
+ inputSchema: {
552
+ type: 'object',
553
+ properties: {}
554
+ }
555
+ },
556
+ {
557
+ name: 'list_directory',
558
+ description: 'Lists files and folders inside the active project directory in a clean tree structure.',
559
+ inputSchema: {
560
+ type: 'object',
561
+ properties: {
562
+ path: {
563
+ type: 'string',
564
+ description: 'Sub-path inside the project directory to list. Default: "."',
565
+ default: '.'
566
+ },
567
+ depth: {
568
+ type: 'number',
569
+ description: 'Folder recursion depth limit (1 to 4). Default: 2',
570
+ default: 2
571
+ }
572
+ }
573
+ }
574
+ },
575
+ {
576
+ name: 'read_file',
577
+ description: 'Reads the content of a file in the project folder with optional line ranges.',
578
+ inputSchema: {
579
+ type: 'object',
580
+ properties: {
581
+ path: {
582
+ type: 'string',
583
+ description: 'Path of the file relative to the project root.'
584
+ },
585
+ start_line: {
586
+ type: 'number',
587
+ description: 'Optional 1-based start line number.'
588
+ },
589
+ end_line: {
590
+ type: 'number',
591
+ description: 'Optional 1-based end line number.'
592
+ }
593
+ },
594
+ required: ['path']
595
+ }
596
+ },
597
+ {
598
+ name: 'write_file',
599
+ description: 'Creates or completely overwrites a file inside the active project folder. Automatically saves a revert snapshot.',
600
+ inputSchema: {
601
+ type: 'object',
602
+ properties: {
603
+ path: {
604
+ type: 'string',
605
+ description: 'Path of the file relative to the project root.'
606
+ },
607
+ content: {
608
+ type: 'string',
609
+ description: 'Full text content to write to the file.'
610
+ }
611
+ },
612
+ required: ['path', 'content']
613
+ }
614
+ },
615
+ {
616
+ name: 'search_files',
617
+ description: 'Searches for text or regex patterns across all code files inside the project folder.',
618
+ inputSchema: {
619
+ type: 'object',
620
+ properties: {
621
+ query: {
622
+ type: 'string',
623
+ description: 'Text string or regex pattern to search for.'
624
+ },
625
+ path: {
626
+ type: 'string',
627
+ description: 'Sub-directory to search within (default: root ".").'
628
+ },
629
+ file_extension: {
630
+ type: 'string',
631
+ description: 'Optional extension filter (e.g. ".py", ".js", ".html").'
632
+ }
633
+ },
634
+ required: ['query']
635
+ }
636
+ },
637
+ {
638
+ name: 'get_file_info',
639
+ description: 'Inspects metadata (file size, total line count, modified date) of a file or directory.',
640
+ inputSchema: {
641
+ type: 'object',
642
+ properties: {
643
+ path: {
644
+ type: 'string',
645
+ description: 'Path to inspect relative to the project root.'
646
+ }
647
+ },
648
+ required: ['path']
649
+ }
650
+ }
651
+ ];
652
+
653
+ const prompts = [
654
+ {
655
+ name: 'deepseek_harness_instructions',
656
+ description: 'Complete DeepSeek Harness autonomous software engineering instructions.',
657
+ arguments: []
658
+ }
659
+ ];
660
+
661
+ function getHarnessInstructions() {
662
+ return `You are operating as an autonomous software engineering agent running inside the complete DeepSeek Harness (dsh) environment.
663
+
664
+ ACTIVE WORKSPACE:
665
+ Directory: "${rootDir}"
666
+
667
+ FULL CAPABILITY SUITE:
668
+ - Subprocess Execution (execute_command): Run linters, unit tests (pytest, npm test), and build tools.
669
+ - Background Services (manage_background_job): Run local servers in background and inspect logs.
670
+ - Dependency Analyzer (inspect_dependencies): Check package.json / requirements.txt to know the tech stack.
671
+ - Git Tracking (git_status, git_diff): Inspect and verify all changes.
672
+ - Atomic Undo (revert_file): Roll back changes if an edit introduced a bug.
673
+ - Web Docs (fetch_web_documentation): Query external API docs when needed.
674
+ - Plan Checklist (manage_plan): Track multi-step tasks.
675
+ - Surgical Editor (edit_file, read_file): Fast, token-efficient code manipulation.
676
+
677
+ RULES:
678
+ 1. Always run tests using execute_command to verify changes.
679
+ 2. Check git_diff before declaring a task finished.
680
+ 3. You are strictly confined to "${rootDir}". All execution runs within this directory.`;
681
+ }
682
+
683
+ // ==========================================
684
+ // 4. Tool Execution Handlers
685
+ // ==========================================
686
+
687
+ async function handleToolCall(name, args) {
688
+ args = args || {};
689
+
690
+ switch (name) {
691
+ // --- 1. Subprocess Execution (dsh-tool-bash, dsh-tool-pwsh) ---
692
+ case 'pwsh':
693
+ case 'bash':
694
+ case 'execute_command': {
695
+ if (isReadOnly) throw new Error('Server running in read-only mode.');
696
+ const cmd = args.command;
697
+ if (!cmd || typeof cmd !== 'string') throw new Error('Command must be a non-empty string.');
698
+
699
+ for (const pattern of BLOCKED_COMMANDS) {
700
+ if (pattern.test(cmd)) {
701
+ throw new Error(`Security Violation: Command "${cmd}" is blocked by DeepSeek safety policies.`);
702
+ }
703
+ }
704
+
705
+ const timeoutMs = Math.min(Math.max(5, (args.timeout_seconds || 30)) * 1000, 60000);
706
+
707
+ return new Promise((resolve) => {
708
+ exec(cmd, {
709
+ cwd: rootDir,
710
+ timeout: timeoutMs,
711
+ maxBuffer: 1024 * 512,
712
+ windowsHide: true
713
+ }, (error, stdout, stderr) => {
714
+ const exitCode = error ? (error.code !== undefined ? error.code : 1) : 0;
715
+ let output = '';
716
+ if (stdout && stdout.trim()) output += `STDOUT:\n${stdout.trim()}\n`;
717
+ if (stderr && stderr.trim()) output += `STDERR:\n${stderr.trim()}\n`;
718
+ if (!output) output = '(Command exited with no output)';
719
+
720
+ resolve(`[DeepSeek Harness Execution]\nCommand: ${cmd}\nExit Code: ${exitCode}\nDirectory: ${rootDir}\n\n${output.trim()}`);
721
+ });
722
+ });
723
+ }
724
+
725
+ // --- 2. Background Jobs (dsh-tool-jobs) ---
726
+ case 'jobs':
727
+ case 'manage_background_job': {
728
+ const action = args.action;
729
+ if (action === 'start') {
730
+ if (isReadOnly) throw new Error('Server running in read-only mode.');
731
+ const cmd = args.command;
732
+ if (!cmd) throw new Error('Must specify command to start background job.');
733
+
734
+ const jobId = nextJobId++;
735
+ const parts = cmd.split(' ');
736
+ const bin = parts[0];
737
+ const cmdArgs = parts.slice(1);
738
+
739
+ const proc = spawn(bin, cmdArgs, {
740
+ cwd: rootDir,
741
+ shell: true,
742
+ windowsHide: true
743
+ });
744
+
745
+ const jobRecord = {
746
+ id: jobId,
747
+ command: cmd,
748
+ startTime: new Date().toISOString(),
749
+ status: 'running',
750
+ logs: []
751
+ };
752
+
753
+ proc.stdout.on('data', d => {
754
+ jobRecord.logs.push(d.toString());
755
+ if (jobRecord.logs.length > 50) jobRecord.logs.shift();
756
+ });
757
+ proc.stderr.on('data', d => {
758
+ jobRecord.logs.push(d.toString());
759
+ if (jobRecord.logs.length > 50) jobRecord.logs.shift();
760
+ });
761
+ proc.on('exit', code => {
762
+ jobRecord.status = `exited with code ${code}`;
763
+ });
764
+
765
+ backgroundJobs.set(jobId, { proc, record: jobRecord });
766
+ return `Started background job #${jobId}: "${cmd}" (PID: ${proc.pid})`;
767
+ } else if (action === 'list') {
768
+ if (backgroundJobs.size === 0) return 'No background jobs currently running.';
769
+ const list = Array.from(backgroundJobs.values()).map(j => `#${j.record.id} [${j.record.status}] "${j.record.command}" (Started: ${j.record.startTime})`);
770
+ return `Active Background Jobs:\n${list.join('\n')}`;
771
+ } else if (action === 'logs') {
772
+ const jobId = args.job_id;
773
+ const job = backgroundJobs.get(jobId);
774
+ if (!job) throw new Error(`Job #${jobId} not found.`);
775
+ return `Recent logs for Job #${jobId} ("${job.record.command}"):\n\n${job.record.logs.join('') || '(No output recorded yet)'}`;
776
+ } else if (action === 'stop') {
777
+ const jobId = args.job_id;
778
+ const job = backgroundJobs.get(jobId);
779
+ if (!job) throw new Error(`Job #${jobId} not found.`);
780
+ try {
781
+ job.proc.kill();
782
+ job.record.status = 'stopped';
783
+ return `Job #${jobId} stopped successfully.`;
784
+ } catch (e) {
785
+ return `Could not stop job #${jobId}: ${e.message}`;
786
+ }
787
+ } else {
788
+ const jobId = args.job_id;
789
+ const job = backgroundJobs.get(jobId);
790
+ if (!job) throw new Error(`Job #${jobId} not found.`);
791
+ return JSON.stringify(job.record, null, 2);
792
+ }
793
+ }
794
+
795
+ // --- 3. Git Tools ---
796
+ case 'git_diff': {
797
+ let cmd = 'git diff';
798
+ if (args.file_path) {
799
+ const resolved = validateAndResolve(args.file_path);
800
+ const rel = path.relative(rootDir, resolved);
801
+ cmd = `git diff -- "${rel}"`;
802
+ }
803
+ return new Promise((resolve) => {
804
+ exec(cmd, { cwd: rootDir, timeout: 10000 }, (error, stdout, stderr) => {
805
+ if (error && !stdout) {
806
+ resolve(`Git diff unavailable: ${stderr || error.message}`);
807
+ } else {
808
+ resolve(stdout.trim() || 'No uncommitted changes detected (clean working tree).');
809
+ }
810
+ });
811
+ });
812
+ }
813
+
814
+ case 'git_status': {
815
+ return new Promise((resolve) => {
816
+ exec('git status --short --branch', { cwd: rootDir, timeout: 10000 }, (error, stdout, stderr) => {
817
+ if (error && !stdout) {
818
+ resolve(`Git status unavailable (not a git repository): ${stderr || error.message}`);
819
+ } else {
820
+ resolve(stdout.trim() || 'Git working tree clean.');
821
+ }
822
+ });
823
+ });
824
+ }
825
+
826
+ // --- 4. Dependency Inspector ---
827
+ case 'inspect_dependencies': {
828
+ const summary = { project_root: rootDir, detected_manifests: {} };
829
+
830
+ // Node.js
831
+ const pkgPath = path.join(rootDir, 'package.json');
832
+ if (fs.existsSync(pkgPath)) {
833
+ try {
834
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
835
+ summary.detected_manifests['Node.js (package.json)'] = {
836
+ name: pkg.name,
837
+ version: pkg.version,
838
+ scripts: pkg.scripts,
839
+ dependencies: pkg.dependencies,
840
+ devDependencies: pkg.devDependencies
841
+ };
842
+ } catch (e) {}
843
+ }
844
+
845
+ // Python requirements
846
+ const reqPath = path.join(rootDir, 'requirements.txt');
847
+ if (fs.existsSync(reqPath)) {
848
+ try {
849
+ const reqs = fs.readFileSync(reqPath, 'utf-8').split(/\r?\n/).filter(l => l.trim() && !l.startsWith('#'));
850
+ summary.detected_manifests['Python (requirements.txt)'] = reqs;
851
+ } catch (e) {}
852
+ }
853
+
854
+ // Python pyproject
855
+ const pyproject = path.join(rootDir, 'pyproject.toml');
856
+ if (fs.existsSync(pyproject)) {
857
+ summary.detected_manifests['Python (pyproject.toml)'] = 'Present';
858
+ }
859
+
860
+ // Rust Cargo.toml
861
+ const cargo = path.join(rootDir, 'Cargo.toml');
862
+ if (fs.existsSync(cargo)) {
863
+ summary.detected_manifests['Rust (Cargo.toml)'] = 'Present';
864
+ }
865
+
866
+ // Go go.mod
867
+ const gomod = path.join(rootDir, 'go.mod');
868
+ if (fs.existsSync(gomod)) {
869
+ summary.detected_manifests['Go (go.mod)'] = 'Present';
870
+ }
871
+
872
+ return JSON.stringify(summary, null, 2);
873
+ }
874
+
875
+ // --- 5. Atomic Edit & Revert (dsh-tool-fs / dsh-tool-str-replace-editor) ---
876
+ case 'edit':
877
+ case 'edit_file': {
878
+ if (isReadOnly) throw new Error('Server running in read-only mode.');
879
+ const filePath = args.file_path || args.path;
880
+ if (!filePath) throw new Error('file_path or path parameter is required.');
881
+ const resolved = validateAndResolve(filePath);
882
+ if (isBinaryFile(resolved)) throw new Error(`Cannot edit binary file "${filePath}".`);
883
+
884
+ const content = fs.readFileSync(resolved, 'utf-8');
885
+ const target = args.old_string !== undefined ? args.old_string : (args.old_str !== undefined ? args.old_str : args.target);
886
+ const replacement = args.new_string !== undefined ? args.new_string : (args.new_str !== undefined ? args.new_str : (args.replacement !== undefined ? args.replacement : ''));
887
+ const replaceAll = args.replace_all || false;
888
+
889
+ if (!target) throw new Error('old_string or target parameter is required.');
890
+ if (!content.includes(target)) {
891
+ throw new Error(`Target snippet not found in "${filePath}". Check whitespace and indentation.`);
892
+ }
893
+
894
+ // Save undo snapshot
895
+ if (!fileBackups.has(resolved)) fileBackups.set(resolved, []);
896
+ fileBackups.get(resolved).push(content);
897
+
898
+ const updated = replaceAll ? content.split(target).join(replacement) : content.replace(target, replacement);
899
+ fs.writeFileSync(resolved, updated, 'utf-8');
900
+ return replaceAll
901
+ ? `The file ${filePath} has been updated. All occurrences were successfully replaced.`
902
+ : `The file ${filePath} has been updated successfully. (Snapshot saved. Can revert with revert_file).`;
903
+ }
904
+
905
+ case 'str_replace_editor': {
906
+ if (isReadOnly && args.command !== 'view') throw new Error('Server running in read-only mode.');
907
+ const cmd = args.command;
908
+ const filePath = args.path || args.file_path;
909
+ if (!filePath) throw new Error('path parameter is required.');
910
+
911
+ if (cmd === 'view') {
912
+ const resolved = validateAndResolve(filePath);
913
+ const stat = fs.statSync(resolved);
914
+ if (stat.isDirectory()) {
915
+ const entries = fs.readdirSync(resolved);
916
+ return `Directory listing for ${filePath}:\n` + entries.slice(0, 50).join('\n');
917
+ }
918
+ const content = fs.readFileSync(resolved, 'utf-8');
919
+ const lines = content.split(/\r?\n/);
920
+ let start = 1;
921
+ let end = lines.length;
922
+ if (Array.isArray(args.view_range) && args.view_range.length === 2) {
923
+ start = Math.max(1, args.view_range[0]);
924
+ end = Math.min(lines.length, args.view_range[1]);
925
+ }
926
+ return lines.slice(start - 1, end).map((l, i) => `${String(start + i).padStart(4, ' ')} | ${l}`).join('\n');
927
+ } else if (cmd === 'create') {
928
+ const resolved = validateAndResolve(filePath, true);
929
+ const dir = path.dirname(resolved);
930
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
931
+ fs.writeFileSync(resolved, args.file_text || '', 'utf-8');
932
+ return `File created successfully at: ${filePath}`;
933
+ } else if (cmd === 'str_replace') {
934
+ const resolved = validateAndResolve(filePath);
935
+ const content = fs.readFileSync(resolved, 'utf-8');
936
+ const oldStr = args.old_str;
937
+ const newStr = args.new_str || '';
938
+ if (!content.includes(oldStr)) throw new Error(`old_str not found in ${filePath}`);
939
+ if (!fileBackups.has(resolved)) fileBackups.set(resolved, []);
940
+ fileBackups.get(resolved).push(content);
941
+ fs.writeFileSync(resolved, content.replace(oldStr, newStr), 'utf-8');
942
+ return `The file ${filePath} has been updated successfully.`;
943
+ } else if (cmd === 'insert') {
944
+ const resolved = validateAndResolve(filePath);
945
+ const content = fs.readFileSync(resolved, 'utf-8');
946
+ const lines = content.split(/\r?\n/);
947
+ const lineNum = Math.max(0, Math.min(lines.length, args.insert_line || 0));
948
+ lines.splice(lineNum, 0, args.new_str || '');
949
+ if (!fileBackups.has(resolved)) fileBackups.set(resolved, []);
950
+ fileBackups.get(resolved).push(content);
951
+ fs.writeFileSync(resolved, lines.join('\n'), 'utf-8');
952
+ return `Inserted content into ${filePath} at line ${lineNum}.`;
953
+ } else {
954
+ throw new Error(`Unknown str_replace_editor command: ${cmd}`);
955
+ }
956
+ }
957
+
958
+ case 'revert_file': {
959
+ if (isReadOnly) throw new Error('Server running in read-only mode.');
960
+ const resolved = validateAndResolve(args.path);
961
+ const history = fileBackups.get(resolved);
962
+
963
+ if (!history || history.length === 0) {
964
+ throw new Error(`No undo snapshots available for "${args.path}".`);
965
+ }
966
+
967
+ const previous = history.pop();
968
+ fs.writeFileSync(resolved, previous, 'utf-8');
969
+ return `Successfully reverted "${args.path}" to previous snapshot. (${history.length} snapshots remaining).`;
970
+ }
971
+
972
+ // --- 6. Web Documentation Fetcher ---
973
+ case 'fetch_web_documentation': {
974
+ const targetUrl = args.url;
975
+ if (!targetUrl || !targetUrl.startsWith('https://')) {
976
+ throw new Error('URL must start with https://');
977
+ }
978
+
979
+ try {
980
+ const response = await fetch(targetUrl, { headers: { 'User-Agent': 'DeepSeek-Harness-Agent/1.0' } });
981
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
982
+ const text = await response.text();
983
+ const clean = text.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
984
+ .replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, '')
985
+ .replace(/<[^>]+>/g, ' ')
986
+ .replace(/\s+/g, ' ')
987
+ .trim();
988
+ return clean.slice(0, 15000);
989
+ } catch (err) {
990
+ throw new Error(`Failed to fetch URL: ${err.message}`);
991
+ }
992
+ }
993
+
994
+ // --- 7. Plan Mode (dsh-plan-mode) ---
995
+ case 'plan_mode':
996
+ case 'manage_plan': {
997
+ const action = args.action;
998
+ if (action === 'set') {
999
+ if (!Array.isArray(args.plan_items)) throw new Error('plan_items must be an array of strings.');
1000
+ currentPlan = args.plan_items.map((item, idx) => ({ id: idx + 1, task: item, completed: false }));
1001
+ return `Plan initialized with ${currentPlan.length} milestones:\n` + currentPlan.map(p => `[ ] ${p.id}. ${p.task}`).join('\n');
1002
+ } else if (action === 'complete_step') {
1003
+ const idx = args.step_index;
1004
+ if (!idx || idx < 1 || idx > currentPlan.length) throw new Error(`Invalid step_index: ${idx}`);
1005
+ currentPlan[idx - 1].completed = true;
1006
+ return `Marked milestone #${idx} as completed.\nCurrent Plan Status:\n` + currentPlan.map(p => `[${p.completed ? 'x' : ' '}] ${p.id}. ${p.task}`).join('\n');
1007
+ } else {
1008
+ if (currentPlan.length === 0) return 'No active plan. Use action="set" with plan_items to initialize a plan.';
1009
+ return 'Current Plan Status:\n' + currentPlan.map(p => `[${p.completed ? 'x' : ' '}] ${p.id}. ${p.task}`).join('\n');
1010
+ }
1011
+ }
1012
+
1013
+ // --- 8. Core Filesystem Tools ---
1014
+ case 'select_project_folder': {
1015
+ let targetPath = args.folder_path;
1016
+ if (!targetPath || targetPath === 'browse' || targetPath === 'picker') {
1017
+ logInfo('Opening native Windows FolderBrowserDialog...');
1018
+ targetPath = openWindowsFolderPicker();
1019
+ if (!targetPath) {
1020
+ return `Folder selection cancelled. Active project remains: "${rootDir}".`;
1021
+ }
1022
+ }
1023
+
1024
+ const resolved = path.resolve(targetPath);
1025
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {
1026
+ throw new Error(`Target path "${targetPath}" is not a valid directory.`);
1027
+ }
1028
+
1029
+ rootDir = fs.realpathSync(resolved);
1030
+ currentPlan = [];
1031
+ fileBackups.clear();
1032
+ logInfo(`Switched project to: ${rootDir}`);
1033
+ return `✓ Project folder successfully set to: "${rootDir}".\nDeepSeek Harness now strictly sandboxed to this folder.`;
1034
+ }
1035
+
1036
+ case 'get_current_project': {
1037
+ let fileCount = 0;
1038
+ let dirCount = 0;
1039
+ try {
1040
+ const entries = fs.readdirSync(rootDir);
1041
+ for (const e of entries) {
1042
+ if (IGNORED_DIRS.has(e)) continue;
1043
+ try {
1044
+ const s = fs.statSync(path.join(rootDir, e));
1045
+ if (s.isDirectory()) dirCount++;
1046
+ else fileCount++;
1047
+ } catch (err) {}
1048
+ }
1049
+ } catch (e) {}
1050
+
1051
+ return JSON.stringify({
1052
+ active_project_path: rootDir,
1053
+ harness: 'DeepSeek Harness (dsh)',
1054
+ modules: [
1055
+ 'dsh-tool-bash (execute_command)',
1056
+ 'dsh-tool-jobs (manage_background_job)',
1057
+ 'dsh-base (git_diff, git_status)',
1058
+ 'dsh-tool-workspace-dependencies (inspect_dependencies)',
1059
+ 'dsh-atomic-write (edit_file, revert_file)',
1060
+ 'dsh-tool-web (fetch_web_documentation)',
1061
+ 'dsh-plan-mode (manage_plan)',
1062
+ 'dsh-tool-fs (read_file, write_file, search_files, list_directory)'
1063
+ ],
1064
+ top_level_files: fileCount,
1065
+ top_level_directories: dirCount,
1066
+ boundary: 'Strictly jailed to this directory alone'
1067
+ }, null, 2);
1068
+ }
1069
+
1070
+ case 'list_directory': {
1071
+ const targetRel = args.path || '.';
1072
+ const maxDepth = Math.min(Math.max(1, args.depth || 2), 4);
1073
+ const resolved = validateAndResolve(targetRel);
1074
+
1075
+ const stat = fs.statSync(resolved);
1076
+ if (!stat.isDirectory()) throw new Error(`"${targetRel}" is a file.`);
1077
+
1078
+ const results = [];
1079
+ function walk(currentDir, currentDepth) {
1080
+ if (currentDepth > maxDepth) return;
1081
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
1082
+
1083
+ for (const entry of entries) {
1084
+ if (entry.name.startsWith('.')) continue;
1085
+ if (entry.isDirectory() && IGNORED_DIRS.has(entry.name)) continue;
1086
+
1087
+ const fullEntryPath = path.join(currentDir, entry.name);
1088
+ const relPath = path.relative(rootDir, fullEntryPath).replace(/\\/g, '/');
1089
+
1090
+ if (entry.isDirectory()) {
1091
+ results.push({ type: 'dir', path: relPath });
1092
+ walk(fullEntryPath, currentDepth + 1);
1093
+ } else {
1094
+ let size = 0;
1095
+ try { size = fs.statSync(fullEntryPath).size; } catch (e) {}
1096
+ results.push({ type: 'file', path: relPath, size });
1097
+ }
1098
+ }
1099
+ }
1100
+
1101
+ walk(resolved, 1);
1102
+ if (results.length === 0) return `Directory "${targetRel}" is empty.`;
1103
+
1104
+ const formatted = results.map(item => item.type === 'dir' ? `[DIR] ${item.path}/` : `[FILE] ${item.path} (${item.size} bytes)`).join('\n');
1105
+ return `Workspace: "${rootDir}"\n\n${formatted}`;
1106
+ }
1107
+
1108
+ case 'read':
1109
+ case 'read_file': {
1110
+ const filePath = args.file_path || args.path;
1111
+ if (!filePath) throw new Error('file_path or path parameter is required.');
1112
+ const resolved = validateAndResolve(filePath);
1113
+ const stat = fs.statSync(resolved);
1114
+ if (stat.isDirectory()) throw new Error(`"${filePath}" is a directory.`);
1115
+ if (isBinaryFile(resolved)) return `[Binary file (${stat.size} bytes) cannot be displayed as text.]`;
1116
+
1117
+ const content = fs.readFileSync(resolved, 'utf-8');
1118
+ const lines = content.split(/\r?\n/);
1119
+ const totalLines = lines.length;
1120
+
1121
+ let startLine = 1;
1122
+ if (args.offset !== undefined) startLine = Math.max(1, parseInt(args.offset, 10));
1123
+ else if (args.start_line !== undefined) startLine = Math.max(1, parseInt(args.start_line, 10));
1124
+
1125
+ let endLine = totalLines;
1126
+ if (args.limit !== undefined) endLine = Math.min(totalLines, startLine + parseInt(args.limit, 10) - 1);
1127
+ else if (args.end_line !== undefined) endLine = Math.min(totalLines, parseInt(args.end_line, 10));
1128
+
1129
+ const slice = lines.slice(startLine - 1, endLine);
1130
+ const outputLines = slice.map((line, idx) => `${String(startLine + idx).padStart(4, ' ')} | ${line}`);
1131
+
1132
+ return `File: ${filePath} (Lines ${startLine}-${endLine} of ${totalLines}):\n\n${outputLines.join('\n')}`;
1133
+ }
1134
+
1135
+ case 'write':
1136
+ case 'write_file': {
1137
+ if (isReadOnly) throw new Error('Server running in read-only mode.');
1138
+ const filePath = args.file_path || args.path;
1139
+ if (!filePath) throw new Error('file_path or path parameter is required.');
1140
+ const resolved = validateAndResolve(filePath, true);
1141
+ const dir = path.dirname(resolved);
1142
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
1143
+
1144
+ // Save undo snapshot if file exists
1145
+ if (fs.existsSync(resolved)) {
1146
+ if (!fileBackups.has(resolved)) fileBackups.set(resolved, []);
1147
+ fileBackups.get(resolved).push(fs.readFileSync(resolved, 'utf-8'));
1148
+ }
1149
+
1150
+ fs.writeFileSync(resolved, args.content !== undefined ? args.content : '', 'utf-8');
1151
+ const stat = fs.statSync(resolved);
1152
+ return `<path>${filePath}</path>\n<type>file</type>\n<content>\n${fs.existsSync(resolved) ? 'Updated' : 'Created'} file (${stat.size} bytes)\n</content>`;
1153
+ }
1154
+
1155
+ case 'search_files': {
1156
+ const targetRel = args.path || '.';
1157
+ const query = args.query;
1158
+ const extFilter = args.file_extension ? args.file_extension.toLowerCase() : null;
1159
+ const resolved = validateAndResolve(targetRel);
1160
+
1161
+ const matches = [];
1162
+ const MAX_MATCHES = 40;
1163
+
1164
+ function searchDir(currentDir) {
1165
+ if (matches.length >= MAX_MATCHES) return;
1166
+ const entries = fs.readdirSync(currentDir, { withFileTypes: true });
1167
+
1168
+ for (const entry of entries) {
1169
+ if (matches.length >= MAX_MATCHES) break;
1170
+ if (entry.name.startsWith('.')) continue;
1171
+ if (entry.isDirectory() && IGNORED_DIRS.has(entry.name)) continue;
1172
+
1173
+ const fullPath = path.join(currentDir, entry.name);
1174
+ if (entry.isDirectory()) {
1175
+ searchDir(fullPath);
1176
+ } else {
1177
+ if (extFilter && !entry.name.toLowerCase().endsWith(extFilter)) continue;
1178
+ if (isBinaryFile(fullPath)) continue;
1179
+
1180
+ try {
1181
+ const fileContent = fs.readFileSync(fullPath, 'utf-8');
1182
+ const lines = fileContent.split(/\r?\n/);
1183
+ for (let i = 0; i < lines.length; i++) {
1184
+ if (matches.length >= MAX_MATCHES) break;
1185
+ if (lines[i].includes(query)) {
1186
+ const rel = path.relative(rootDir, fullPath).replace(/\\/g, '/');
1187
+ matches.push(`${rel}:${i + 1}: ${lines[i].trim()}`);
1188
+ }
1189
+ }
1190
+ } catch (e) {}
1191
+ }
1192
+ }
1193
+ }
1194
+
1195
+ searchDir(resolved);
1196
+ if (matches.length === 0) return `No matches found for "${query}".`;
1197
+ return `Search results for "${query}":\n\n${matches.join('\n')}`;
1198
+ }
1199
+
1200
+ case 'get_file_info': {
1201
+ const resolved = validateAndResolve(args.path);
1202
+ const stat = fs.statSync(resolved);
1203
+ return JSON.stringify({
1204
+ path: args.path,
1205
+ is_directory: stat.isDirectory(),
1206
+ size_bytes: stat.size,
1207
+ modified: stat.mtime
1208
+ }, null, 2);
1209
+ }
1210
+
1211
+ default:
1212
+ throw new Error(`Unknown tool: ${name}`);
1213
+ }
1214
+ }
1215
+
1216
+ // ==========================================
1217
+ // 5. JSON-RPC Protocol Processor (Shared)
1218
+ // ==========================================
1219
+
1220
+ async function processJsonRpcMessage(msg) {
1221
+ const { id, method, params } = msg;
1222
+
1223
+ if (method === 'initialize') {
1224
+ return {
1225
+ jsonrpc: '2.0',
1226
+ id,
1227
+ result: {
1228
+ protocolVersion: '2024-11-05',
1229
+ capabilities: {
1230
+ tools: { listChanged: true },
1231
+ prompts: { listChanged: true }
1232
+ },
1233
+ serverInfo: {
1234
+ name: 'deepseek-harness-mcp',
1235
+ version: '3.5.0'
1236
+ }
1237
+ }
1238
+ };
1239
+ }
1240
+
1241
+ if (method === 'notifications/initialized') {
1242
+ return null;
1243
+ }
1244
+
1245
+ if (method === 'ping') {
1246
+ return { jsonrpc: '2.0', id, result: {} };
1247
+ }
1248
+
1249
+ if (method === 'tools/list') {
1250
+ return { jsonrpc: '2.0', id, result: { tools } };
1251
+ }
1252
+
1253
+ if (method === 'tools/call') {
1254
+ const { name, arguments: toolArgs } = params || {};
1255
+ try {
1256
+ const resultText = await handleToolCall(name, toolArgs);
1257
+ return {
1258
+ jsonrpc: '2.0',
1259
+ id,
1260
+ result: {
1261
+ content: [{ type: 'text', text: typeof resultText === 'string' ? resultText : JSON.stringify(resultText) }],
1262
+ isError: false
1263
+ }
1264
+ };
1265
+ } catch (err) {
1266
+ return {
1267
+ jsonrpc: '2.0',
1268
+ id,
1269
+ result: {
1270
+ content: [{ type: 'text', text: `Error: ${err.message}` }],
1271
+ isError: true
1272
+ }
1273
+ };
1274
+ }
1275
+ }
1276
+
1277
+ if (method === 'prompts/list') {
1278
+ return { jsonrpc: '2.0', id, result: { prompts } };
1279
+ }
1280
+
1281
+ if (method === 'prompts/get') {
1282
+ return {
1283
+ jsonrpc: '2.0',
1284
+ id,
1285
+ result: {
1286
+ description: 'DeepSeek Harness Instructions',
1287
+ messages: [{ role: 'user', content: { type: 'text', text: getHarnessInstructions() } }]
1288
+ }
1289
+ };
1290
+ }
1291
+
1292
+ return {
1293
+ jsonrpc: '2.0',
1294
+ id,
1295
+ error: { code: -32601, message: `Method not found: ${method}` }
1296
+ };
1297
+ }
1298
+
1299
+ // ==========================================
1300
+ // 6. HTTP Transport (Gemini, Claude, ChatGPT)
1301
+ // ==========================================
1302
+
1303
+ function startHttpServer(port) {
1304
+ logInfo(`Starting Complete DeepSeek-Harness MCP Server on port ${port}...`);
1305
+ logInfo(`Current Sandboxed Folder: ${rootDir}`);
1306
+
1307
+ const server = http.createServer(async (req, res) => {
1308
+ res.setHeader('Access-Control-Allow-Origin', '*');
1309
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
1310
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Accept, x-mcp-version, mcp-session-id');
1311
+
1312
+ if (req.method === 'OPTIONS') {
1313
+ res.writeHead(204);
1314
+ res.end();
1315
+ return;
1316
+ }
1317
+
1318
+ const url = new URL(req.url, `http://${req.headers.host}`);
1319
+
1320
+ if (req.method === 'GET' && (url.pathname === '/mcp' || url.pathname === '/')) {
1321
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1322
+ res.end(JSON.stringify({
1323
+ status: 'online',
1324
+ service: 'DeepSeek Harness Complete MCP Suite',
1325
+ protocolVersion: '2024-11-05',
1326
+ activeProject: rootDir,
1327
+ toolsCount: tools.length,
1328
+ tools: tools.map(t => t.name)
1329
+ }, null, 2));
1330
+ return;
1331
+ }
1332
+
1333
+ if (req.method === 'GET' && url.pathname === '/openapi.json') {
1334
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1335
+ res.end(JSON.stringify({
1336
+ openapi: '3.1.0',
1337
+ info: {
1338
+ title: 'DeepSeek Harness MCP API',
1339
+ description: 'Full software engineering harness: execution, background jobs, git, dependency analysis, atomic undo, and filesystem.',
1340
+ version: '3.5.0'
1341
+ },
1342
+ servers: [{ url: `https://${req.headers.host}` }],
1343
+ paths: {
1344
+ '/call': {
1345
+ post: {
1346
+ summary: 'Execute a DeepSeek Harness tool',
1347
+ operationId: 'executeTool',
1348
+ requestBody: {
1349
+ required: true,
1350
+ content: {
1351
+ 'application/json': {
1352
+ schema: {
1353
+ type: 'object',
1354
+ properties: {
1355
+ name: { type: 'string', enum: tools.map(t => t.name) },
1356
+ arguments: { type: 'object' }
1357
+ },
1358
+ required: ['name', 'arguments']
1359
+ }
1360
+ }
1361
+ }
1362
+ },
1363
+ responses: {
1364
+ '200': {
1365
+ description: 'Tool result',
1366
+ content: {
1367
+ 'application/json': {
1368
+ schema: {
1369
+ type: 'object',
1370
+ properties: {
1371
+ success: { type: 'boolean' },
1372
+ result: { type: 'string' },
1373
+ error: { type: 'string' }
1374
+ }
1375
+ }
1376
+ }
1377
+ }
1378
+ }
1379
+ }
1380
+ }
1381
+ }
1382
+ }
1383
+ }, null, 2));
1384
+ return;
1385
+ }
1386
+
1387
+ if (req.method === 'GET' && url.pathname === '/api/status') {
1388
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1389
+ res.end(JSON.stringify({
1390
+ status: 'online',
1391
+ activeProject: rootDir,
1392
+ toolsCount: tools.length,
1393
+ isReadOnly: isReadOnly,
1394
+ uptime: process.uptime()
1395
+ }));
1396
+ return;
1397
+ }
1398
+
1399
+ if (req.method === 'POST' && url.pathname === '/api/set-directory') {
1400
+ let body = '';
1401
+ req.on('data', chunk => { body += chunk; });
1402
+ req.on('end', () => {
1403
+ try {
1404
+ const payload = JSON.parse(body);
1405
+ let targetPath = payload.path;
1406
+ if (!targetPath) throw new Error('Missing path parameter.');
1407
+ const resolved = path.resolve(targetPath);
1408
+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {
1409
+ throw new Error(`Directory "${targetPath}" does not exist.`);
1410
+ }
1411
+ rootDir = fs.realpathSync(resolved);
1412
+ currentPlan = [];
1413
+ fileBackups.clear();
1414
+ logInfo(`Switched project directory via CLI to: ${rootDir}`);
1415
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1416
+ res.end(JSON.stringify({ success: true, activeProject: rootDir }));
1417
+ } catch (err) {
1418
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1419
+ res.end(JSON.stringify({ success: false, error: err.message }));
1420
+ }
1421
+ });
1422
+ return;
1423
+ }
1424
+
1425
+ if (req.method === 'POST' && url.pathname === '/call') {
1426
+ let body = '';
1427
+ req.on('data', chunk => { body += chunk; });
1428
+ req.on('end', async () => {
1429
+ try {
1430
+ const payload = JSON.parse(body);
1431
+ const result = await handleToolCall(payload.name, payload.arguments);
1432
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1433
+ res.end(JSON.stringify({ success: true, result }));
1434
+ } catch (err) {
1435
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1436
+ res.end(JSON.stringify({ success: false, error: err.message }));
1437
+ }
1438
+ });
1439
+ return;
1440
+ }
1441
+
1442
+ if (req.method === 'POST' && (url.pathname === '/mcp' || url.pathname === '/')) {
1443
+ let body = '';
1444
+ req.on('data', chunk => { body += chunk; });
1445
+ req.on('end', async () => {
1446
+ try {
1447
+ const msg = JSON.parse(body);
1448
+ const response = await processJsonRpcMessage(msg);
1449
+ if (response) {
1450
+ res.writeHead(200, { 'Content-Type': 'application/json' });
1451
+ res.end(JSON.stringify(response));
1452
+ } else {
1453
+ res.writeHead(204);
1454
+ res.end();
1455
+ }
1456
+ } catch (e) {
1457
+ res.writeHead(400, { 'Content-Type': 'application/json' });
1458
+ res.end(JSON.stringify({
1459
+ jsonrpc: '2.0',
1460
+ id: null,
1461
+ error: { code: -32700, message: 'Parse error: invalid JSON' }
1462
+ }));
1463
+ }
1464
+ });
1465
+ return;
1466
+ }
1467
+
1468
+ res.writeHead(404, { 'Content-Type': 'application/json' });
1469
+ res.end(JSON.stringify({ error: 'Endpoint not found. Use /mcp' }));
1470
+ });
1471
+
1472
+ server.listen(port, () => {
1473
+ logInfo(`Complete DeepSeek Harness listening on port ${port}`);
1474
+ });
1475
+ }
1476
+
1477
+ // ==========================================
1478
+ // 7. Stdio Transport
1479
+ // ==========================================
1480
+
1481
+ function startStdioServer() {
1482
+ logInfo(`Starting Stdio DeepSeek-Harness Server...`);
1483
+ logInfo(`Current Sandboxed Folder: ${rootDir}`);
1484
+
1485
+ const rl = readline.createInterface({
1486
+ input: process.stdin,
1487
+ output: process.stdout,
1488
+ terminal: false
1489
+ });
1490
+
1491
+ rl.on('line', async (line) => {
1492
+ const trimmed = line.trim();
1493
+ if (!trimmed) return;
1494
+
1495
+ try {
1496
+ const msg = JSON.parse(trimmed);
1497
+ const response = await processJsonRpcMessage(msg);
1498
+ if (response) {
1499
+ process.stdout.write(JSON.stringify(response) + '\n');
1500
+ }
1501
+ } catch (e) {
1502
+ process.stdout.write(JSON.stringify({
1503
+ jsonrpc: '2.0',
1504
+ id: null,
1505
+ error: { code: -32700, message: 'Parse error' }
1506
+ }) + '\n');
1507
+ }
1508
+ });
1509
+ }
1510
+
1511
+ // ==========================================
1512
+ // 8. Launch
1513
+ // ==========================================
1514
+
1515
+ if (httpPort) {
1516
+ startHttpServer(httpPort);
1517
+ } else {
1518
+ startStdioServer();
1519
+ }