dev-terminal-app 0.1.0__tar.gz

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,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: dev-terminal-app
3
+ Version: 0.1.0
4
+ Summary: An AI-Native Developer CLI
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+
8
+ # dev_cli
9
+ An AI-Native Developer CLI.
@@ -0,0 +1,2 @@
1
+ # dev_cli
2
+ An AI-Native Developer CLI.
@@ -0,0 +1,664 @@
1
+ import os
2
+ import json
3
+ import re
4
+ import subprocess
5
+ import difflib
6
+ from pathlib import Path
7
+
8
+ import ollama
9
+ import ai
10
+
11
+
12
+ # ─────────────────────────────────────────────
13
+ # Project
14
+ # ─────────────────────────────────────────────
15
+
16
+ PROJECT_ROOT = Path.cwd().resolve()
17
+
18
+
19
+ def safe_path(path):
20
+ target = (PROJECT_ROOT / path).resolve()
21
+
22
+ try:
23
+ target.relative_to(PROJECT_ROOT)
24
+ except ValueError:
25
+ return None
26
+
27
+ return target
28
+
29
+
30
+ # ─────────────────────────────────────────────
31
+ # File tools
32
+ # ─────────────────────────────────────────────
33
+
34
+ def read_file(path):
35
+ target = safe_path(path)
36
+
37
+ if target is None:
38
+ return "ERROR: Access outside the project directory is not allowed."
39
+
40
+ if not target.exists():
41
+ return f"ERROR: File does not exist: {path}"
42
+
43
+ if not target.is_file():
44
+ return f"ERROR: Not a file: {path}"
45
+
46
+ try:
47
+ return target.read_text()
48
+ except Exception as e:
49
+ return f"ERROR reading {path}: {e}"
50
+
51
+
52
+ def list_files(path="."):
53
+ target = safe_path(path)
54
+
55
+ if target is None:
56
+ return "ERROR: Access outside the project directory is not allowed."
57
+
58
+ if not target.exists():
59
+ return f"ERROR: Directory does not exist: {path}"
60
+
61
+ if not target.is_dir():
62
+ return f"ERROR: Not a directory: {path}"
63
+
64
+ ignored = {
65
+ ".git",
66
+ ".venv",
67
+ "venv",
68
+ "node_modules",
69
+ "__pycache__",
70
+ ".next",
71
+ "dist",
72
+ "build",
73
+ }
74
+
75
+ files = []
76
+
77
+ for item in sorted(target.rglob("*")):
78
+ try:
79
+ relative = item.relative_to(PROJECT_ROOT)
80
+ except ValueError:
81
+ continue
82
+
83
+ if any(part in ignored for part in relative.parts):
84
+ continue
85
+
86
+ if item.is_file():
87
+ files.append(str(relative))
88
+
89
+ if not files:
90
+ return "Project contains no visible files."
91
+
92
+ return "\n".join(files[:500])
93
+
94
+
95
+ def search_files(query):
96
+ query = query.strip()
97
+
98
+ if not query:
99
+ return "ERROR: Search query cannot be empty."
100
+
101
+ ignored = {
102
+ ".git",
103
+ ".venv",
104
+ "venv",
105
+ "node_modules",
106
+ "__pycache__",
107
+ ".next",
108
+ "dist",
109
+ "build",
110
+ }
111
+
112
+ results = []
113
+
114
+ for path in PROJECT_ROOT.rglob("*"):
115
+ if not path.is_file():
116
+ continue
117
+
118
+ try:
119
+ relative = path.relative_to(PROJECT_ROOT)
120
+ except ValueError:
121
+ continue
122
+
123
+ if any(part in ignored for part in relative.parts):
124
+ continue
125
+
126
+ try:
127
+ text = path.read_text()
128
+ except Exception:
129
+ continue
130
+
131
+ if query.lower() in text.lower():
132
+ results.append(str(relative))
133
+
134
+ if len(results) >= 100:
135
+ break
136
+
137
+ if not results:
138
+ return f"No files found containing: {query}"
139
+
140
+ return "\n".join(results)
141
+
142
+
143
+ # ─────────────────────────────────────────────
144
+ # Diff / write
145
+ # ─────────────────────────────────────────────
146
+
147
+ def show_diff(path, old_content, new_content):
148
+ diff = difflib.unified_diff(
149
+ old_content.splitlines(),
150
+ new_content.splitlines(),
151
+ fromfile=path,
152
+ tofile=path,
153
+ lineterm="",
154
+ )
155
+
156
+ lines = list(diff)
157
+
158
+ if not lines:
159
+ return False
160
+
161
+ print()
162
+ print("DEV • PROPOSED CHANGE")
163
+ print("────────────────────────────────────────")
164
+ print()
165
+
166
+ for line in lines:
167
+ if line.startswith("+++"):
168
+ print(f"\033[32m{line}\033[0m")
169
+ elif line.startswith("---"):
170
+ print(f"\033[31m{line}\033[0m")
171
+ elif line.startswith("@@"):
172
+ print(f"\033[36m{line}\033[0m")
173
+ elif line.startswith("+"):
174
+ print(f"\033[32m{line}\033[0m")
175
+ elif line.startswith("-"):
176
+ print(f"\033[31m{line}\033[0m")
177
+ else:
178
+ print(line)
179
+
180
+ print()
181
+ return True
182
+
183
+
184
+ def write_file(path, content):
185
+ target = safe_path(path)
186
+
187
+ if target is None:
188
+ return "ERROR: Access outside the project directory is not allowed."
189
+
190
+ old_content = ""
191
+
192
+ if target.exists():
193
+ if not target.is_file():
194
+ return f"ERROR: Not a file: {path}"
195
+
196
+ try:
197
+ old_content = target.read_text()
198
+ except Exception as e:
199
+ return f"ERROR reading existing file: {e}"
200
+
201
+ show_diff(path, old_content, content)
202
+
203
+ if target.exists():
204
+ print(f"DEV • AGENT wants to modify: {path}")
205
+ else:
206
+ print(f"DEV • AGENT wants to create: {path}")
207
+
208
+ print()
209
+
210
+ answer = input("Apply this change? [y/N] ").strip().lower()
211
+
212
+ if answer != "y":
213
+ return "WRITE CANCELLED BY USER."
214
+
215
+ try:
216
+ target.parent.mkdir(parents=True, exist_ok=True)
217
+ target.write_text(content)
218
+ return f"Successfully wrote {path}"
219
+ except Exception as e:
220
+ return f"ERROR writing {path}: {e}"
221
+
222
+
223
+ # ─────────────────────────────────────────────
224
+ # Command tool
225
+ # ─────────────────────────────────────────────
226
+
227
+ def run_command(command):
228
+ print()
229
+ print("DEV • AGENT wants to run:")
230
+ print()
231
+ print(f" {command}")
232
+ print()
233
+
234
+ answer = input("Run this command? [y/N] ").strip().lower()
235
+
236
+ if answer != "y":
237
+ return "COMMAND CANCELLED BY USER."
238
+
239
+ try:
240
+ shell = os.environ.get("SHELL", "/bin/zsh")
241
+
242
+ result = subprocess.run(
243
+ command,
244
+ shell=True,
245
+ executable=shell,
246
+ cwd=PROJECT_ROOT,
247
+ capture_output=True,
248
+ text=True,
249
+ )
250
+
251
+ output = result.stdout + result.stderr
252
+
253
+ if len(output) > 12000:
254
+ output = output[-12000:]
255
+
256
+ return (
257
+ f"Exit code: {result.returncode}\n"
258
+ f"Output:\n{output}"
259
+ )
260
+
261
+ except Exception as e:
262
+ return f"ERROR running command: {e}"
263
+
264
+
265
+ # ─────────────────────────────────────────────
266
+ # Tools
267
+ # ─────────────────────────────────────────────
268
+
269
+ TOOLS = [
270
+ {
271
+ "type": "function",
272
+ "function": {
273
+ "name": "read_file",
274
+ "description": "Read a text file inside the current project.",
275
+ "parameters": {
276
+ "type": "object",
277
+ "properties": {
278
+ "path": {
279
+ "type": "string",
280
+ },
281
+ },
282
+ "required": ["path"],
283
+ },
284
+ },
285
+ },
286
+ {
287
+ "type": "function",
288
+ "function": {
289
+ "name": "list_files",
290
+ "description": "List files in the current project.",
291
+ "parameters": {
292
+ "type": "object",
293
+ "properties": {
294
+ "path": {
295
+ "type": "string",
296
+ },
297
+ },
298
+ "required": [],
299
+ },
300
+ },
301
+ },
302
+ {
303
+ "type": "function",
304
+ "function": {
305
+ "name": "search_files",
306
+ "description": "Search project files for text.",
307
+ "parameters": {
308
+ "type": "object",
309
+ "properties": {
310
+ "query": {
311
+ "type": "string",
312
+ },
313
+ },
314
+ "required": ["query"],
315
+ },
316
+ },
317
+ },
318
+ {
319
+ "type": "function",
320
+ "function": {
321
+ "name": "write_file",
322
+ "description": "Create or replace a text file. Always inspect existing files first.",
323
+ "parameters": {
324
+ "type": "object",
325
+ "properties": {
326
+ "path": {
327
+ "type": "string",
328
+ },
329
+ "content": {
330
+ "type": "string",
331
+ },
332
+ },
333
+ "required": ["path", "content"],
334
+ },
335
+ },
336
+ },
337
+ {
338
+ "type": "function",
339
+ "function": {
340
+ "name": "run_command",
341
+ "description": "Run a shell command inside the current project directory.",
342
+ "parameters": {
343
+ "type": "object",
344
+ "properties": {
345
+ "command": {
346
+ "type": "string",
347
+ },
348
+ },
349
+ "required": ["command"],
350
+ },
351
+ },
352
+ },
353
+ ]
354
+
355
+
356
+ TOOL_FUNCTIONS = {
357
+ "read_file": read_file,
358
+ "list_files": list_files,
359
+ "search_files": search_files,
360
+ "write_file": write_file,
361
+ "run_command": run_command,
362
+ }
363
+
364
+
365
+ # ─────────────────────────────────────────────
366
+ # Tool-call parsing
367
+ # ─────────────────────────────────────────────
368
+
369
+ def parse_text_tool_calls(text):
370
+ """
371
+ Handles models that return tool calls as JSON inside message content.
372
+
373
+ Example:
374
+
375
+ [
376
+ {
377
+ "name": "write_file",
378
+ "arguments": {
379
+ "path": "hello.py",
380
+ "content": "print('hello world')"
381
+ }
382
+ }
383
+ ]
384
+ """
385
+
386
+ if not text:
387
+ return []
388
+
389
+ text = text.strip()
390
+
391
+ candidates = [text]
392
+
393
+ # Handle markdown code fences
394
+ fenced = re.findall(
395
+ r"```(?:json)?\s*(.*?)```",
396
+ text,
397
+ flags=re.DOTALL | re.IGNORECASE,
398
+ )
399
+
400
+ candidates.extend(fenced)
401
+
402
+ for candidate in candidates:
403
+ candidate = candidate.strip()
404
+
405
+ try:
406
+ data = json.loads(candidate)
407
+ except Exception:
408
+ continue
409
+
410
+ if isinstance(data, dict):
411
+ data = [data]
412
+
413
+ if not isinstance(data, list):
414
+ continue
415
+
416
+ calls = []
417
+
418
+ for item in data:
419
+ if not isinstance(item, dict):
420
+ continue
421
+
422
+ name = item.get("name")
423
+
424
+ if not name:
425
+ function = item.get("function", {})
426
+ name = function.get("name")
427
+
428
+ arguments = item.get("arguments", {})
429
+
430
+ if not arguments:
431
+ function = item.get("function", {})
432
+ arguments = function.get("arguments", {})
433
+
434
+ if isinstance(arguments, str):
435
+ try:
436
+ arguments = json.loads(arguments)
437
+ except Exception:
438
+ continue
439
+
440
+ if name and isinstance(arguments, dict):
441
+ calls.append(
442
+ {
443
+ "name": name,
444
+ "arguments": arguments,
445
+ }
446
+ )
447
+
448
+ if calls:
449
+ return calls
450
+
451
+ return []
452
+
453
+
454
+ # ─────────────────────────────────────────────
455
+ # Agent prompt
456
+ # ─────────────────────────────────────────────
457
+
458
+ SYSTEM_PROMPT = """
459
+ You are DEV Agent, an autonomous coding agent.
460
+
461
+ You are operating inside the user's current project directory.
462
+
463
+ Available tools:
464
+
465
+ - list_files(path)
466
+ - search_files(query)
467
+ - read_file(path)
468
+ - write_file(path, content)
469
+ - run_command(command)
470
+
471
+ Rules:
472
+
473
+ 1. Understand the project before changing it.
474
+ 2. Use tools instead of merely describing what you would do.
475
+ 3. Read relevant files before modifying them.
476
+ 4. Never modify files outside the current project.
477
+ 5. Make the smallest reasonable changes.
478
+ 6. After making changes, run appropriate tests when useful.
479
+ 7. Never claim a change was made unless write_file succeeded.
480
+ 8. Never claim a command succeeded unless its result shows success.
481
+ 9. The user must approve every file modification.
482
+ 10. The user must approve every shell command.
483
+ 11. If the task is simple, do not overcomplicate it.
484
+ 12. Finish the user's requested task.
485
+ 13. If you need to create a file, actually use write_file.
486
+ 14. If you need to test something, actually use run_command.
487
+ 15. Do not output fake tool calls as ordinary text.
488
+ 16. When tools are available, use them.
489
+ """
490
+
491
+
492
+ # ─────────────────────────────────────────────
493
+ # Execute tool
494
+ # ─────────────────────────────────────────────
495
+
496
+ def execute_tool(name, arguments):
497
+ tool = TOOL_FUNCTIONS.get(name)
498
+
499
+ if tool is None:
500
+ return f"ERROR: Unknown tool {name}"
501
+
502
+ print()
503
+ print(
504
+ f"DEV • AGENT → {name}"
505
+ )
506
+
507
+ try:
508
+ return tool(**arguments)
509
+ except Exception as e:
510
+ return f"ERROR executing tool: {e}"
511
+
512
+
513
+ # ─────────────────────────────────────────────
514
+ # Agent
515
+ # ─────────────────────────────────────────────
516
+
517
+ def agent(prompt):
518
+ messages = [
519
+ {
520
+ "role": "system",
521
+ "content": SYSTEM_PROMPT,
522
+ },
523
+ {
524
+ "role": "user",
525
+ "content": prompt,
526
+ },
527
+ ]
528
+
529
+ max_steps = 20
530
+
531
+ for _ in range(max_steps):
532
+
533
+ response = ollama.chat(
534
+ model=ai.MODEL,
535
+ messages=messages,
536
+ tools=TOOLS,
537
+ )
538
+
539
+ message = response["message"]
540
+
541
+ native_tool_calls = message.get(
542
+ "tool_calls",
543
+ [],
544
+ )
545
+
546
+ text = message.get(
547
+ "content",
548
+ "",
549
+ )
550
+
551
+ parsed_text_calls = parse_text_tool_calls(text)
552
+
553
+ # ─────────────────────────────────────
554
+ # Native Ollama tool calls
555
+ # ─────────────────────────────────────
556
+
557
+ if native_tool_calls:
558
+
559
+ messages.append(message)
560
+
561
+ for tool_call in native_tool_calls:
562
+ function = tool_call["function"]
563
+
564
+ name = function["name"]
565
+ arguments = function.get(
566
+ "arguments",
567
+ {},
568
+ )
569
+
570
+ if isinstance(arguments, str):
571
+ arguments = json.loads(arguments)
572
+
573
+ result = execute_tool(
574
+ name,
575
+ arguments,
576
+ )
577
+
578
+ messages.append(
579
+ {
580
+ "role": "tool",
581
+ "content": str(result),
582
+ }
583
+ )
584
+
585
+ continue
586
+
587
+ # ─────────────────────────────────────
588
+ # Text-based tool calls
589
+ # ─────────────────────────────────────
590
+
591
+ if parsed_text_calls:
592
+
593
+ # Do not display raw JSON to the user.
594
+ messages.append(
595
+ {
596
+ "role": "assistant",
597
+ "content": text,
598
+ }
599
+ )
600
+
601
+ for call in parsed_text_calls:
602
+ result = execute_tool(
603
+ call["name"],
604
+ call["arguments"],
605
+ )
606
+
607
+ messages.append(
608
+ {
609
+ "role": "user",
610
+ "content": (
611
+ f"Tool result for "
612
+ f"{call['name']}:\n"
613
+ f"{result}"
614
+ ),
615
+ }
616
+ )
617
+
618
+ continue
619
+
620
+ # ─────────────────────────────────────
621
+ # Normal response
622
+ # ─────────────────────────────────────
623
+
624
+ if text:
625
+ print()
626
+ print(text)
627
+
628
+ break
629
+
630
+ else:
631
+ print()
632
+ print(
633
+ "\033[33m"
634
+ "Agent stopped after reaching its step limit."
635
+ "\033[0m"
636
+ )
637
+
638
+
639
+ # ─────────────────────────────────────────────
640
+ # Standalone mode
641
+ # ─────────────────────────────────────────────
642
+
643
+ def main():
644
+ print()
645
+ print("DEV • AGENT")
646
+ print("────────────────────────────────────────")
647
+ print(f"Model: {ai.MODEL}")
648
+ print(f"Project: {PROJECT_ROOT}")
649
+ print()
650
+
651
+ prompt = input(
652
+ "What should I work on?\n\n"
653
+ "DEV/agent > "
654
+ )
655
+
656
+ if not prompt.strip():
657
+ return
658
+
659
+ agent(prompt)
660
+
661
+
662
+ if __name__ == "__main__":
663
+ ai.ensure_model()
664
+ main()