alpiecode 10.7.3__tar.gz → 10.7.5__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.
Files changed (63) hide show
  1. {alpiecode-10.7.3 → alpiecode-10.7.5}/PKG-INFO +1 -1
  2. {alpiecode-10.7.3 → alpiecode-10.7.5}/pyproject.toml +1 -1
  3. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/alpiecode.egg-info/PKG-INFO +1 -1
  4. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/alpiecode.egg-info/SOURCES.txt +5 -0
  5. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/__init__.py +1 -1
  6. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/agent.py +36 -62
  7. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/backends/openai_backend.py +7 -3
  8. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/cache.py +7 -4
  9. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/cli.py +2 -2
  10. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/config.py +61 -33
  11. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/context.py +19 -9
  12. alpiecode-10.7.5/src/codeagent/diff_preview.py +77 -0
  13. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/local_model.py +13 -13
  14. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/orchestrator.py +80 -39
  15. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/prompt.py +42 -35
  16. alpiecode-10.7.5/src/codeagent/slash.py +208 -0
  17. alpiecode-10.7.5/src/codeagent/subagent.py +269 -0
  18. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/system1.py +33 -21
  19. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/tools.py +39 -0
  20. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/verifier.py +44 -0
  21. alpiecode-10.7.5/test/test_slash_and_diff.py +78 -0
  22. alpiecode-10.7.5/test/test_subagents.py +93 -0
  23. {alpiecode-10.7.3 → alpiecode-10.7.5}/test/test_verifier.py +16 -1
  24. {alpiecode-10.7.3 → alpiecode-10.7.5}/README.md +0 -0
  25. {alpiecode-10.7.3 → alpiecode-10.7.5}/setup.cfg +0 -0
  26. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/alpiecode/__init__.py +0 -0
  27. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/alpiecode.egg-info/dependency_links.txt +0 -0
  28. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/alpiecode.egg-info/entry_points.txt +0 -0
  29. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/alpiecode.egg-info/requires.txt +0 -0
  30. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/alpiecode.egg-info/top_level.txt +0 -0
  31. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/assessment.py +0 -0
  32. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/backends/__init__.py +0 -0
  33. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/backends/base.py +0 -0
  34. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/backends/local_backend.py +0 -0
  35. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/client.py +0 -0
  36. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/compaction.py +0 -0
  37. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/discovery.py +0 -0
  38. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/doctor.py +0 -0
  39. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/dream_rsi.py +0 -0
  40. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/executor.py +0 -0
  41. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/extension/alpiecode.vsix +0 -0
  42. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/git_ops.py +0 -0
  43. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/github.py +0 -0
  44. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/guardian.py +0 -0
  45. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/guardrails.py +0 -0
  46. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/ipython_ext.py +0 -0
  47. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/media.py +0 -0
  48. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/memory.py +0 -0
  49. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/metrics.py +0 -0
  50. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/paths.py +0 -0
  51. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/progress.py +0 -0
  52. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/rephraser.py +0 -0
  53. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/server.py +0 -0
  54. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/session.py +0 -0
  55. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/updater.py +0 -0
  56. {alpiecode-10.7.3 → alpiecode-10.7.5}/src/codeagent/vscode_installer.py +0 -0
  57. {alpiecode-10.7.3 → alpiecode-10.7.5}/test/test_adaptive_resilience.py +0 -0
  58. {alpiecode-10.7.3 → alpiecode-10.7.5}/test/test_cli_ui.py +0 -0
  59. {alpiecode-10.7.3 → alpiecode-10.7.5}/test/test_context_and_trajectory.py +0 -0
  60. {alpiecode-10.7.3 → alpiecode-10.7.5}/test/test_dream_rsi.py +0 -0
  61. {alpiecode-10.7.3 → alpiecode-10.7.5}/test/test_local_model_download.py +0 -0
  62. {alpiecode-10.7.3 → alpiecode-10.7.5}/test/test_non_thinking_and_local_stream.py +0 -0
  63. {alpiecode-10.7.3 → alpiecode-10.7.5}/test/test_task_assessment.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.7.3
3
+ Version: 10.7.5
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "alpiecode"
7
- version = "10.7.3"
7
+ version = "10.7.5"
8
8
  description = "AlpieCode"
9
9
  requires-python = ">=3.9"
10
10
  dependencies = [
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.7.3
3
+ Version: 10.7.5
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -16,6 +16,7 @@ src/codeagent/client.py
16
16
  src/codeagent/compaction.py
17
17
  src/codeagent/config.py
18
18
  src/codeagent/context.py
19
+ src/codeagent/diff_preview.py
19
20
  src/codeagent/discovery.py
20
21
  src/codeagent/doctor.py
21
22
  src/codeagent/dream_rsi.py
@@ -36,6 +37,8 @@ src/codeagent/prompt.py
36
37
  src/codeagent/rephraser.py
37
38
  src/codeagent/server.py
38
39
  src/codeagent/session.py
40
+ src/codeagent/slash.py
41
+ src/codeagent/subagent.py
39
42
  src/codeagent/system1.py
40
43
  src/codeagent/tools.py
41
44
  src/codeagent/updater.py
@@ -52,5 +55,7 @@ test/test_context_and_trajectory.py
52
55
  test/test_dream_rsi.py
53
56
  test/test_local_model_download.py
54
57
  test/test_non_thinking_and_local_stream.py
58
+ test/test_slash_and_diff.py
59
+ test/test_subagents.py
55
60
  test/test_task_assessment.py
56
61
  test/test_verifier.py
@@ -17,7 +17,7 @@ Supports:
17
17
  from pathlib import Path
18
18
  from typing import Optional, Any, Dict
19
19
 
20
- __version__ = "10.7.3"
20
+ __version__ = "10.7.5"
21
21
 
22
22
  def run(task: str, workdir: str = ".", reasoning_level: str = "thinking", **kwargs):
23
23
  """Run an autonomous coding task programmatically."""
@@ -73,28 +73,38 @@ def _print_reasoning(reasoning: str):
73
73
  console.print(f"💭 {clean}")
74
74
 
75
75
 
76
+ def _format_bash_summary(args: dict) -> str:
77
+ cmd = args.get("command", "").strip()
78
+ return f"$ {cmd[:80]}..." if len(cmd) > 80 else f"$ {cmd}"
79
+
80
+
81
+ def _format_file_summary(args: dict, name: str) -> str:
82
+ path = args.get("path", "")
83
+ extra = f" ({len(str(args['content']).splitlines())} lines)" if name == "write_file" and "content" in args else ""
84
+ return f"{path}{extra}"
85
+
86
+
87
+ TOOL_SUMMARY_FORMATTERS = {
88
+ "bash": _format_bash_summary,
89
+ "write_file": lambda a: _format_file_summary(a, "write_file"),
90
+ "edit_file": lambda a: _format_file_summary(a, "edit_file"),
91
+ "read_file": lambda a: _format_file_summary(a, "read_file"),
92
+ "list_files": lambda a: a.get("path", "."),
93
+ "search": lambda a: f"'{a.get('query', '')}'",
94
+ "web_search": lambda a: f"'{a.get('query', '')}'",
95
+ "fetch_web_page": lambda a: a.get("url", ""),
96
+ "invoke_subagent": lambda a: f"🤖 {a.get('subagent', 'agent')}: '{a.get('prompt', '')[:50]}'",
97
+ }
98
+
99
+
76
100
  def _format_tool_summary(name: str, args: dict) -> str:
77
101
  if not isinstance(args, dict):
78
102
  return ""
79
- if name == "bash":
80
- cmd = args.get("command", "").strip()
81
- return f"$ {cmd[:80]}..." if len(cmd) > 80 else f"$ {cmd}"
82
- elif name in ("write_file", "edit_file", "read_file"):
83
- path = args.get("path", "")
84
- extra = ""
85
- if name == "write_file" and "content" in args:
86
- lines = len(str(args["content"]).splitlines())
87
- extra = f" ({lines} lines)"
88
- return f"{path}{extra}"
89
- elif name == "list_files":
90
- return args.get("path", ".")
91
- elif name in ("search", "web_search"):
92
- return f"'{args.get('query', '')}'"
93
- elif name == "fetch_web_page":
94
- return args.get("url", "")
95
- else:
96
- parts = [f"{k}={repr(v)[:30]}" for k, v in args.items() if k != "content"]
97
- return " ".join(parts)
103
+ formatter = TOOL_SUMMARY_FORMATTERS.get(name)
104
+ if formatter:
105
+ return formatter(args)
106
+ parts = [f"{k}={repr(v)[:30]}" for k, v in args.items() if k != "content"]
107
+ return " ".join(parts)
98
108
 
99
109
 
100
110
  def _print_tool_call(turn: int, name: str, args: dict):
@@ -744,7 +754,8 @@ def run_chat(workdir: Path, cfg: Config, verbose: bool = True, debug: bool = Fal
744
754
 
745
755
  if HAS_RICH:
746
756
  console.print()
747
- mode_line = "🌐 Mode: [bold green]ONLINE[/bold green]\n🤖 Model: [bold cyan]alpie_9b[/bold cyan]" if not is_offline else "🧠 Mode: [bold yellow]OFFLINE[/bold yellow]\n🤖 Model: [bold cyan]alpie_9b (Local GGUF)[/bold cyan]"
757
+ cur_model = getattr(cfg, "model", "alpie_seed")
758
+ mode_line = f"🌐 Mode: [bold green]ONLINE[/bold green]\n🤖 Model: [bold cyan]{cur_model}[/bold cyan]" if not is_offline else f"🧠 Mode: [bold yellow]OFFLINE[/bold yellow]\n🤖 Model: [bold cyan]{cur_model} (Local GGUF)[/bold cyan]"
748
759
  console.print(
749
760
  Panel(
750
761
  f"[bold cyan]AlpieCode[/bold cyan] interactive mode\n"
@@ -771,50 +782,13 @@ def run_chat(workdir: Path, cfg: Config, verbose: bool = True, debug: bool = Fal
771
782
 
772
783
  if not user_input:
773
784
  continue
774
- if user_input.lower() in ("exit", "quit", "q"):
785
+ # In-chat slash commands (/help, /status, /diff, /undo, /doctor, /research, /review, /test, /clear, /subagents)
786
+ from .slash import handle_slash_command
787
+ slash_res = handle_slash_command(user_input, session, orchestrator, cfg, console, has_rich=HAS_RICH)
788
+ if slash_res is False:
775
789
  console.print("Goodbye! 👋")
776
790
  break
777
-
778
- # In-chat slash commands
779
- if user_input.lower() in ("/clear", "/reset"):
780
- session = session_mgr.create_session(
781
- workdir,
782
- max_tokens=backend.context_window if hasattr(backend, 'context_window') and backend.context_window else (cfg.n_ctx if cfg.base_url == 'offline' else 262_144)
783
- )
784
- if HAS_RICH:
785
- console.print("[bold green]✨ Conversation context reset.[/bold green]")
786
- else:
787
- print("✨ Conversation context reset.")
788
- continue
789
-
790
- if user_input.lower() in ("/info", "/status"):
791
- mode_str = "OFFLINE (Local GGUF)" if is_offline else "ONLINE (Cloud API)"
792
- ctx_tokens = backend.context_window if hasattr(backend, 'context_window') and backend.context_window else cfg.n_ctx
793
- user_turns = len([m for m in session.context.messages if m.get("role") == "user"])
794
- info_msg = (
795
- f"[bold]AlpieCode Session Info[/bold]\n"
796
- f" • Mode: {mode_str}\n"
797
- f" • Working Dir: {workdir}\n"
798
- f" • Context Window: {ctx_tokens} tokens\n"
799
- f" • Session Turns: {user_turns}"
800
- )
801
- if HAS_RICH:
802
- console.print(Panel(info_msg, border_style="cyan", title="ℹ️ Status"))
803
- else:
804
- print(info_msg)
805
- continue
806
-
807
- if user_input.lower() in ("/help", "/?"):
808
- help_msg = (
809
- "Available commands:\n"
810
- " • /clear, /reset - Reset conversation memory\n"
811
- " • /info, /status - View current model and session diagnostics\n"
812
- " • exit, quit, q - Exit interactive chat"
813
- )
814
- if HAS_RICH:
815
- console.print(Panel(help_msg, border_style="dim", title="Help"))
816
- else:
817
- print(help_msg)
791
+ elif slash_res is True:
818
792
  continue
819
793
 
820
794
  has_streamed_chat = False
@@ -39,12 +39,16 @@ def _dict_to_obj(d: Any) -> Any:
39
39
  return d
40
40
 
41
41
 
42
- PRIMARY_DOMAIN = "test.169pi.ai"
43
- PRIMARY_IP = "20.245.200.125"
42
+ PRIMARY_DOMAIN = "ec2-18-222-121-38.us-east-2.compute.amazonaws.com"
43
+ PRIMARY_IP = "18.222.121.38"
44
44
 
45
45
 
46
46
  def _make_fallback_ip_url(url: str) -> str:
47
- return url.replace(f"https://{PRIMARY_DOMAIN}", f"https://{PRIMARY_IP}")
47
+ if PRIMARY_DOMAIN in url:
48
+ return url.replace(PRIMARY_DOMAIN, PRIMARY_IP)
49
+ if "test.169pi.ai" in url:
50
+ return url.replace("https://test.169pi.ai", "https://20.245.200.125")
51
+ return url
48
52
 
49
53
 
50
54
  class _HTTPXChatCompletions:
@@ -289,10 +289,13 @@ class TestResultCache:
289
289
  def _get_workspace_fingerprint(self, workdir: Path) -> str:
290
290
  try:
291
291
  mtimes = []
292
- for ext in ("*.py", "*.js", "*.ts", "*.json"):
293
- for p in workdir.glob(ext):
294
- if p.is_file() and not p.name.startswith("."):
295
- mtimes.append(f"{p.name}:{p.stat().st_mtime_ns}")
292
+ valid_exts = {".py", ".js", ".ts", ".json"}
293
+ with os.scandir(workdir) as it:
294
+ for entry in it:
295
+ if entry.is_file() and not entry.name.startswith("."):
296
+ dot_idx = entry.name.rfind(".")
297
+ if dot_idx != -1 and entry.name[dot_idx:] in valid_exts:
298
+ mtimes.append(f"{entry.name}:{entry.stat().st_mtime_ns}")
296
299
  return hashlib.md5("".join(sorted(mtimes)).encode()).hexdigest()[:12]
297
300
  except Exception:
298
301
  return "0"
@@ -98,9 +98,9 @@ def main():
98
98
  common.add_argument("--github", default=None, help="GitHub repository (e.g. owner/repo or URL) for open-source analysis")
99
99
  common.add_argument("--max-turns", type=int, default=None, help="Override max turns")
100
100
  common.add_argument("--endpoint", "--base-url", dest="endpoint", default=None, help="VLM API endpoint base URL")
101
- common.add_argument("--model", dest="model", default=None, help="Model name (e.g. alpie_9b)")
101
+ common.add_argument("--model", dest="model", default=None, help="Model name (e.g. alpie_seed, alpie_9b)")
102
102
  common.add_argument("--api-key", dest="api_key", default=None, help="API key for endpoint authentication")
103
- common.add_argument("--preset", dest="preset", choices=["default", "alpie_9b"], default=None, help="Endpoint preset profile")
103
+ common.add_argument("--preset", dest="preset", choices=["default", "alpie_seed", "alpie_9b"], default=None, help="Endpoint preset profile")
104
104
  common.add_argument("--thinking", "--reasoning", dest="thinking", action="store_true", help="Enable VLM reasoning mode")
105
105
  common.add_argument("--no-thinking", "--non-thinking", dest="no_thinking", action="store_true", help="Disable VLM reasoning mode")
106
106
  common.add_argument("--force-thinking", dest="force_thinking", action="store_true", help="Force VLM reasoning on all turns, disabling dynamic gating")
@@ -12,7 +12,8 @@ import os
12
12
  import socket
13
13
  from dataclasses import dataclass, asdict, fields
14
14
  from pathlib import Path
15
- from typing import Optional
15
+ import time
16
+ from typing import Optional, Dict, Tuple
16
17
 
17
18
  from .paths import ensure_dir, get_alpiecode_dir, is_android, is_ios, load_dotenv_if_present
18
19
 
@@ -43,7 +44,7 @@ CONFIG_DIR = get_alpiecode_dir()
43
44
  CONFIG_PATH = get_config_path()
44
45
 
45
46
  # Config version — bump this when defaults change to trigger auto-migration
46
- CONFIG_VERSION = 11 # v11: Embedded zero-friction token fallback + DNS/IP resilience
47
+ CONFIG_VERSION = 12 # v12: Switched primary cloud endpoint to AWS EC2 alpie_seed
47
48
 
48
49
  # Embedded Hugging Face token: provides 100% out-of-the-box functionality for end users
49
50
  # Can be overridden via .env or HF_TOKEN / HUGGING_FACE_HUB_TOKEN environment variables
@@ -52,8 +53,8 @@ DEFAULT_HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HU
52
53
  DEFAULT_MODEL_REPO = "169Pi/alpie_learn_gguf"
53
54
 
54
55
  DEFAULTS = {
55
- "base_url": "https://test.169pi.ai/v1", # Primary endpoint
56
- "model": "alpie_9b",
56
+ "base_url": "http://ec2-18-222-121-38.us-east-2.compute.amazonaws.com:8000/v1", # Primary endpoint
57
+ "model": "alpie_seed",
57
58
  "model_repo": DEFAULT_MODEL_REPO,
58
59
  "api_key": "not-needed",
59
60
  "hf_token": DEFAULT_HF_TOKEN,
@@ -63,6 +64,7 @@ DEFAULTS = {
63
64
  "enable_thinking": False, # Reasoning OFF by default
64
65
  "adaptive_thinking": True, # Adaptive turn-level reasoning dynamics
65
66
  "force_thinking": False, # Force reasoning on every single turn
67
+ "force_no_thinking": False, # Fast execution mode
66
68
  "n_ctx": 32768, # 32k context window
67
69
  "n_gpu_layers": None, # None = auto-detect GPU
68
70
  "config_version": CONFIG_VERSION,
@@ -70,8 +72,13 @@ DEFAULTS = {
70
72
 
71
73
  KNOWN_PRESETS = {
72
74
  "default": {
73
- "base_url": "https://test.169pi.ai/v1",
74
- "model": "alpie_9b",
75
+ "base_url": "http://ec2-18-222-121-38.us-east-2.compute.amazonaws.com:8000/v1",
76
+ "model": "alpie_seed",
77
+ "api_key": "not-needed",
78
+ },
79
+ "alpie_seed": {
80
+ "base_url": "http://ec2-18-222-121-38.us-east-2.compute.amazonaws.com:8000/v1",
81
+ "model": "alpie_seed",
75
82
  "api_key": "not-needed",
76
83
  },
77
84
  "alpie_9b": {
@@ -82,36 +89,57 @@ KNOWN_PRESETS = {
82
89
  }
83
90
 
84
91
 
92
+ _SERVER_REACHABLE_CACHE: Dict[Tuple[str, float], Tuple[float, bool]] = {}
93
+
94
+
85
95
  def is_server_reachable(base_url: Optional[str], timeout: float = 0.5) -> bool:
86
- """Fast network ping check to see if server endpoint is online with DNS fallback."""
96
+ """Fast network ping check to see if server endpoint is online with DNS fallback (5s TTL cache)."""
87
97
  if not base_url:
88
98
  return False
89
- try:
90
- from urllib.parse import urlparse
91
- parsed = urlparse(base_url)
92
- host = parsed.hostname
93
- port = parsed.port or (443 if parsed.scheme == "https" else 80)
94
- if not host:
95
- return False
99
+ now = time.time()
100
+ cache_key = (base_url, timeout)
101
+ if cache_key in _SERVER_REACHABLE_CACHE:
102
+ cached_time, cached_res = _SERVER_REACHABLE_CACHE[cache_key]
103
+ if now - cached_time < 5.0:
104
+ return cached_res
105
+
106
+ def _check() -> bool:
96
107
  try:
97
- with socket.create_connection((host, port), timeout=timeout):
98
- return True
99
- except (socket.gaierror, OSError):
100
- # Resilient IP fallback for test.169pi.ai on mobile/iOS where DNS might fail ([Errno 8])
101
- if host == "test.169pi.ai":
102
- try:
103
- with socket.create_connection(("20.245.200.125", port), timeout=timeout):
104
- return True
105
- except Exception:
106
- pass
108
+ from urllib.parse import urlparse
109
+ parsed = urlparse(base_url)
110
+ host = parsed.hostname
111
+ port = parsed.port or (443 if parsed.scheme == "https" else 80)
112
+ if not host:
113
+ return False
114
+ try:
115
+ with socket.create_connection((host, port), timeout=timeout):
116
+ return True
117
+ except (socket.gaierror, OSError):
118
+ # Resilient IP fallback for AWS EC2 / test.169pi.ai on mobile/iOS where DNS might fail ([Errno 8])
119
+ if host and "ec2-18-222-121-38" in host:
120
+ try:
121
+ with socket.create_connection(("18.222.121.38", port), timeout=timeout):
122
+ return True
123
+ except Exception:
124
+ pass
125
+ elif host == "test.169pi.ai":
126
+ try:
127
+ with socket.create_connection(("20.245.200.125", port), timeout=timeout):
128
+ return True
129
+ except Exception:
130
+ pass
131
+ return False
132
+ except Exception:
107
133
  return False
108
- except Exception:
109
- return False
134
+
135
+ res = _check()
136
+ _SERVER_REACHABLE_CACHE[cache_key] = (now, res)
137
+ return res
110
138
 
111
139
 
112
140
  def is_internet_available(timeout: float = 1.0) -> bool:
113
- """Quick check if general internet is available (tries DNS and HTTPS IP)."""
114
- for host, port in [("8.8.8.8", 53), ("1.1.1.1", 53), ("20.245.200.125", 443)]:
141
+ """Quick check if general internet is available (tries DNS and active cloud endpoint)."""
142
+ for host, port in [("8.8.8.8", 53), ("1.1.1.1", 53), ("18.222.121.38", 8000)]:
115
143
  try:
116
144
  with socket.create_connection((host, port), timeout=timeout):
117
145
  return True
@@ -150,7 +178,7 @@ def get_shared_http_client():
150
178
  @dataclass
151
179
  class Config:
152
180
  base_url: Optional[str] = None
153
- model: str = "alpie_9b" # Server API model name (vLLM)
181
+ model: str = "alpie_seed" # Server API model name (vLLM)
154
182
  model_repo: str = DEFAULT_MODEL_REPO # HuggingFace repo for offline GGUF
155
183
  api_key: str = "not-needed"
156
184
  hf_token: Optional[str] = DEFAULT_HF_TOKEN
@@ -177,11 +205,11 @@ def load_config() -> Config:
177
205
 
178
206
  # ── Auto-migrate stale configs ────────────────────────────
179
207
  saved_version = saved_data.get("config_version", 1)
180
- if saved_version < CONFIG_VERSION or "20.245.200.125" in str(saved_data.get("base_url", "")):
208
+ if saved_version < CONFIG_VERSION or "test.169pi.ai" in str(saved_data.get("base_url", "")) or "20.245.200.125" in str(saved_data.get("base_url", "")):
181
209
  if saved_data.get("n_ctx") == 16384:
182
210
  data["n_ctx"] = 32768
183
- data["base_url"] = "https://test.169pi.ai/v1"
184
- data["model"] = "alpie_9b"
211
+ data["base_url"] = "http://ec2-18-222-121-38.us-east-2.compute.amazonaws.com:8000/v1"
212
+ data["model"] = "alpie_seed"
185
213
  data["model_repo"] = DEFAULT_MODEL_REPO
186
214
  data["hf_token"] = DEFAULT_HF_TOKEN
187
215
  data["enable_thinking"] = False
@@ -309,7 +337,7 @@ def interactive_init() -> Config:
309
337
  if b.is_available:
310
338
  print("✅ iOS local engine ready (in-app llama.cpp or local bridge active).")
311
339
  else:
312
- print("ℹ️ iOS Inference: Online model endpoint (https://test.169pi.ai) is configured.")
340
+ print(f"ℹ️ iOS Inference: Online model endpoint ({cfg.base_url}) is configured.")
313
341
  print(" For offline inference on iOS, launch an in-app bridge (http://127.0.0.1:8080).")
314
342
  elif is_android():
315
343
  print("\n⚙️ Configuring inference engine for Android...")
@@ -58,6 +58,7 @@ class ContextManager:
58
58
  self._messages: List[dict] = []
59
59
  self._raw_messages: List[dict] = []
60
60
  self._metadata: List[Dict[str, Any]] = []
61
+ self._tool_id_to_name: Dict[str, str] = {}
61
62
  self._turn_counter: int = 0
62
63
  self._cached_summary: Optional[str] = None
63
64
  self._cached_summary_len: int = 0
@@ -100,19 +101,22 @@ class ContextManager:
100
101
  tokens = self._estimate_single_message_tokens(msg)
101
102
  content_str = str(msg.get("content") or "")
102
103
 
103
- # Infer tool name if not provided
104
+ # Infer tool name if not provided (O(1) lookup with backward scan fallback)
104
105
  resolved_tool_name = tool_name
105
106
  if role == "tool" and not resolved_tool_name:
106
107
  t_id = msg.get("tool_call_id", "")
107
- for prev in reversed(self._messages):
108
- if prev.get("role") == "assistant" and prev.get("tool_calls"):
109
- for tc in prev["tool_calls"]:
110
- tc_dict = tc if isinstance(tc, dict) else {}
111
- if tc_dict.get("id") == t_id:
112
- resolved_tool_name = tc_dict.get("function", {}).get("name")
108
+ if t_id and t_id in self._tool_id_to_name:
109
+ resolved_tool_name = self._tool_id_to_name[t_id]
110
+ else:
111
+ for prev in reversed(self._messages):
112
+ if prev.get("role") == "assistant" and prev.get("tool_calls"):
113
+ for tc in prev["tool_calls"]:
114
+ tc_dict = tc if isinstance(tc, dict) else {}
115
+ if tc_dict.get("id") == t_id:
116
+ resolved_tool_name = tc_dict.get("function", {}).get("name")
117
+ break
118
+ if resolved_tool_name:
113
119
  break
114
- if resolved_tool_name:
115
- break
116
120
 
117
121
  # Infer importance
118
122
  resolved_importance = importance
@@ -183,6 +187,12 @@ class ContextManager:
183
187
  """Append an assistant response with tool calls and record metadata."""
184
188
  if response.tool_calls or response.content:
185
189
  self.invalidate_cache()
190
+ if response.tool_calls:
191
+ for tc in response.tool_calls:
192
+ tc_id = getattr(tc, "id", None) or (tc.get("id") if isinstance(tc, dict) else None)
193
+ tc_name = getattr(tc, "name", None) or (tc.get("function", {}).get("name") if isinstance(tc, dict) else None)
194
+ if tc_id and tc_name:
195
+ self._tool_id_to_name[tc_id] = tc_name
186
196
  msg = _serialize_assistant_message(response)
187
197
  self._messages.append(dict(msg))
188
198
  self._raw_messages.append(copy.deepcopy(msg))
@@ -0,0 +1,77 @@
1
+ """
2
+ Interactive Diff Previewer and Formatter for AlpieCode.
3
+
4
+ Provides Git-style unified diff generation with Rich syntax highlighting:
5
+ - Green for additions (+)
6
+ - Red for deletions (-)
7
+ - Cyan for chunk headers (@@ ... @@)
8
+ """
9
+
10
+ import difflib
11
+ from pathlib import Path
12
+ from typing import Optional, Tuple
13
+
14
+
15
+ def generate_unified_diff(
16
+ original: str,
17
+ modified: str,
18
+ filepath: str = "file",
19
+ context_lines: int = 3,
20
+ ) -> str:
21
+ """Generate a standard unified diff string between original and modified text."""
22
+ orig_lines = original.splitlines(keepends=True)
23
+ mod_lines = modified.splitlines(keepends=True)
24
+
25
+ diff = difflib.unified_diff(
26
+ orig_lines,
27
+ mod_lines,
28
+ fromfile=f"a/{filepath}",
29
+ tofile=f"b/{filepath}",
30
+ n=context_lines,
31
+ )
32
+ return "".join(diff)
33
+
34
+
35
+ def format_colored_diff(diff_text: str, has_rich: bool = True) -> str:
36
+ """Format unified diff text with terminal color codes or Rich markup."""
37
+ if not diff_text or not diff_text.strip():
38
+ return "[dim]No changes detected.[/dim]" if has_rich else "No changes detected."
39
+
40
+ formatted_lines = []
41
+ for line in diff_text.splitlines():
42
+ if line.startswith("+++") or line.startswith("---"):
43
+ formatted_lines.append(f"[bold white]{line}[/bold white]" if has_rich else line)
44
+ elif line.startswith("@@"):
45
+ formatted_lines.append(f"[bold cyan]{line}[/bold cyan]" if has_rich else line)
46
+ elif line.startswith("+"):
47
+ formatted_lines.append(f"[green]{line}[/green]" if has_rich else line)
48
+ elif line.startswith("-"):
49
+ formatted_lines.append(f"[red]{line}[/red]" if has_rich else line)
50
+ else:
51
+ formatted_lines.append(f"[dim]{line}[/dim]" if has_rich else line)
52
+
53
+ return "\n".join(formatted_lines)
54
+
55
+
56
+ def get_git_diff_summary(workdir: Path) -> Tuple[str, int, int]:
57
+ """Inspect git diff of working directory and compute additions and deletions count."""
58
+ import subprocess
59
+ try:
60
+ res = subprocess.run(
61
+ ["git", "diff", "HEAD"],
62
+ cwd=str(workdir),
63
+ capture_output=True,
64
+ text=True,
65
+ timeout=5,
66
+ )
67
+ diff_text = res.stdout if res.returncode == 0 else ""
68
+ additions = 0
69
+ deletions = 0
70
+ for line in diff_text.splitlines():
71
+ if line.startswith("+") and not line.startswith("+++"):
72
+ additions += 1
73
+ elif line.startswith("-") and not line.startswith("---"):
74
+ deletions += 1
75
+ return diff_text, additions, deletions
76
+ except Exception:
77
+ return "", 0, 0
@@ -19,6 +19,12 @@ load_dotenv_if_present()
19
19
 
20
20
 
21
21
  def get_model_cache_dir() -> Path:
22
+ custom = os.environ.get("ALPIECODE_MODELS_DIR")
23
+ if custom:
24
+ return Path(custom)
25
+ home_models = Path.home() / ".alpiecode" / "models"
26
+ if home_models.exists():
27
+ return home_models
22
28
  return get_alpiecode_dir() / "models"
23
29
 
24
30
 
@@ -130,21 +136,11 @@ def download_model(repo_id: str = DEFAULT_REPO, token: Optional[str] = None) ->
130
136
  OFFLINE-FIRST: Checks local cache for BOTH text and vision models before network calls.
131
137
  """
132
138
  cache_dir = ensure_dir(get_model_cache_dir())
133
- home_models_dir = Path.home() / ".alpiecode" / "models"
134
139
  raw_token = token or os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or DEFAULT_HF_TOKEN or EMBEDDED_HF_TOKEN
135
140
  hf_token = raw_token.strip() if (isinstance(raw_token, str) and raw_token.strip()) else None
136
141
 
137
142
  # ── STEP 1: Check local cache FIRST (zero network) ───────────────
138
- search_dirs = [cache_dir]
139
- if home_models_dir.exists() and home_models_dir != cache_dir:
140
- search_dirs.append(home_models_dir)
141
-
142
- local_ggufs = []
143
- for s_dir in search_dirs:
144
- for g in s_dir.glob("*.gguf"):
145
- if not g.name.endswith(".defective.bak") and g not in local_ggufs:
146
- local_ggufs.append(g)
147
-
143
+ local_ggufs = [g for g in cache_dir.glob("*.gguf") if not g.name.endswith(".defective.bak")]
148
144
  local_main_candidates = [f for f in local_ggufs if "mmproj" not in f.name.lower()]
149
145
  local_mmproj_candidates = [f for f in local_ggufs if "mmproj" in f.name.lower()]
150
146
 
@@ -154,8 +150,12 @@ def download_model(repo_id: str = DEFAULT_REPO, token: Optional[str] = None) ->
154
150
  active_local_main = local_q3_ks[0] if local_q3_ks else (local_q3_m[0] if local_q3_m else (local_main_candidates[0] if local_main_candidates else None))
155
151
  active_local_mmproj = local_mmproj_candidates[0] if local_mmproj_candidates else None
156
152
 
157
- # If text model is already present in cache, return immediately (offline-first)!
158
- if active_local_main:
153
+ # If BOTH text model and vision projector are present, return immediately
154
+ if active_local_main and active_local_mmproj:
155
+ return active_local_main
156
+
157
+ # If text model is present and does not require a vision projector (pure text model), return immediately
158
+ if active_local_main and "mmproj" not in repo_id.lower() and not ("vl" in active_local_main.name.lower() or "vl" in repo_id.lower()):
159
159
  return active_local_main
160
160
 
161
161
  # ── STEP 2: One or both models missing — download from HuggingFace ────