alpiecode 10.5.9__tar.gz → 10.6.1__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 (58) hide show
  1. {alpiecode-10.5.9 → alpiecode-10.6.1}/PKG-INFO +1 -1
  2. {alpiecode-10.5.9 → alpiecode-10.6.1}/pyproject.toml +1 -1
  3. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/alpiecode.egg-info/PKG-INFO +1 -1
  4. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/alpiecode.egg-info/SOURCES.txt +1 -0
  5. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/__init__.py +1 -1
  6. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/backends/local_backend.py +283 -7
  7. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/config.py +23 -20
  8. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/local_model.py +92 -55
  9. alpiecode-10.6.1/src/codeagent/paths.py +115 -0
  10. alpiecode-10.6.1/test/test_local_model_download.py +238 -0
  11. alpiecode-10.5.9/src/codeagent/paths.py +0 -40
  12. {alpiecode-10.5.9 → alpiecode-10.6.1}/README.md +0 -0
  13. {alpiecode-10.5.9 → alpiecode-10.6.1}/setup.cfg +0 -0
  14. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/alpiecode/__init__.py +0 -0
  15. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/alpiecode.egg-info/dependency_links.txt +0 -0
  16. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/alpiecode.egg-info/entry_points.txt +0 -0
  17. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/alpiecode.egg-info/requires.txt +0 -0
  18. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/alpiecode.egg-info/top_level.txt +0 -0
  19. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/agent.py +0 -0
  20. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/assessment.py +0 -0
  21. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/backends/__init__.py +0 -0
  22. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/backends/base.py +0 -0
  23. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/backends/openai_backend.py +0 -0
  24. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/cache.py +0 -0
  25. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/cli.py +0 -0
  26. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/client.py +0 -0
  27. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/compaction.py +0 -0
  28. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/context.py +0 -0
  29. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/discovery.py +0 -0
  30. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/doctor.py +0 -0
  31. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/dream_rsi.py +0 -0
  32. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/executor.py +0 -0
  33. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/extension/alpiecode.vsix +0 -0
  34. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/git_ops.py +0 -0
  35. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/github.py +0 -0
  36. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/guardian.py +0 -0
  37. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/guardrails.py +0 -0
  38. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/ipython_ext.py +0 -0
  39. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/media.py +0 -0
  40. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/memory.py +0 -0
  41. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/metrics.py +0 -0
  42. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/orchestrator.py +0 -0
  43. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/progress.py +0 -0
  44. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/prompt.py +0 -0
  45. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/rephraser.py +0 -0
  46. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/server.py +0 -0
  47. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/session.py +0 -0
  48. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/system1.py +0 -0
  49. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/tools.py +0 -0
  50. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/updater.py +0 -0
  51. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/verifier.py +0 -0
  52. {alpiecode-10.5.9 → alpiecode-10.6.1}/src/codeagent/vscode_installer.py +0 -0
  53. {alpiecode-10.5.9 → alpiecode-10.6.1}/test/test_adaptive_resilience.py +0 -0
  54. {alpiecode-10.5.9 → alpiecode-10.6.1}/test/test_cli_ui.py +0 -0
  55. {alpiecode-10.5.9 → alpiecode-10.6.1}/test/test_context_and_trajectory.py +0 -0
  56. {alpiecode-10.5.9 → alpiecode-10.6.1}/test/test_dream_rsi.py +0 -0
  57. {alpiecode-10.5.9 → alpiecode-10.6.1}/test/test_task_assessment.py +0 -0
  58. {alpiecode-10.5.9 → alpiecode-10.6.1}/test/test_verifier.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.5.9
3
+ Version: 10.6.1
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.5.9"
7
+ version = "10.6.1"
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.5.9
3
+ Version: 10.6.1
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -50,5 +50,6 @@ test/test_adaptive_resilience.py
50
50
  test/test_cli_ui.py
51
51
  test/test_context_and_trajectory.py
52
52
  test/test_dream_rsi.py
53
+ test/test_local_model_download.py
53
54
  test/test_task_assessment.py
54
55
  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.5.9"
20
+ __version__ = "10.6.1"
21
21
 
22
22
  def run(task: str, workdir: str = ".", reasoning_level: str = "thinking", **kwargs):
23
23
  """Run an autonomous coding task programmatically."""
@@ -1,28 +1,41 @@
1
- """
2
- Local GGUF model inference backend.
3
- """
4
-
1
+ import os
2
+ import shutil
3
+ import sys
5
4
  from typing import Any, List, Optional
6
5
 
7
6
  from ..config import Config
8
7
  from ..local_model import LocalModel
8
+ from ..paths import is_android, is_ios
9
9
  from .base import ChatResponse, ToolCall
10
10
 
11
11
 
12
12
  class LocalBackend:
13
- """Backend for local GGUF model inference via llama-cpp-python."""
13
+ """
14
+ Local GGUF model inference backend.
15
+ Factory and base class for platform-specific inference backends (iOS, Android, Windows, macOS, Linux).
16
+ """
17
+
18
+ def __new__(cls, cfg: Config, *args, **kwargs):
19
+ if cls is LocalBackend or cls.__name__ == "BasePlatformBackend":
20
+ return get_platform_backend(cfg)
21
+ return super().__new__(cls)
14
22
 
15
23
  def __init__(self, cfg: Config):
16
24
  self._cfg = cfg
17
25
  self._model: Optional[LocalModel] = None
18
26
 
27
+ @property
28
+ def platform_name(self) -> str:
29
+ return "Generic"
30
+
19
31
  @property
20
32
  def name(self) -> str:
21
- return f"Local GGUF ({self._cfg.model_repo})"
33
+ return f"Local GGUF ({self.platform_name} - {self._cfg.model_repo})"
22
34
 
23
35
  @property
24
36
  def is_available(self) -> bool:
25
- return True # Local model is always available (downloads if missing)
37
+ return True
38
+
26
39
 
27
40
  @property
28
41
  def context_window(self) -> int:
@@ -389,3 +402,266 @@ class LocalBackend:
389
402
  if self._model:
390
403
  self._model._llm = None
391
404
  self._model = None
405
+
406
+
407
+ BasePlatformBackend = LocalBackend
408
+
409
+
410
+ class iOSBackend(BasePlatformBackend):
411
+ """
412
+ iOS-specific inference backend.
413
+
414
+ Guarantees zero dynamic compilation and zero pip install execution.
415
+ Communicates with pre-bundled llama.cpp or a local in-app HTTP bridge.
416
+ """
417
+
418
+ @property
419
+ def platform_name(self) -> str:
420
+ return "iOS"
421
+
422
+ @property
423
+ def is_available(self) -> bool:
424
+ try:
425
+ import llama_cpp
426
+ return True
427
+ except ImportError:
428
+ return self._is_bridge_online()
429
+
430
+ def _get_bridge_url(self) -> str:
431
+ return os.environ.get("IOS_LLAMA_BRIDGE", "http://127.0.0.1:8080").rstrip("/")
432
+
433
+ def _is_bridge_online(self) -> bool:
434
+ try:
435
+ import httpx
436
+ r = httpx.get(f"{self._get_bridge_url()}/v1/models", timeout=0.3)
437
+ return r.status_code == 200
438
+ except Exception:
439
+ return False
440
+
441
+ def chat_completion(
442
+ self,
443
+ messages: List[dict],
444
+ tools: Optional[List[dict]] = None,
445
+ temperature: float = 0.2,
446
+ max_tokens: int = 2048,
447
+ enable_thinking: bool = True,
448
+ ) -> ChatResponse:
449
+ try:
450
+ import llama_cpp
451
+ return super().chat_completion(messages, tools, temperature, max_tokens, enable_thinking)
452
+ except ImportError:
453
+ pass
454
+
455
+ if self._is_bridge_online():
456
+ return self._bridge_chat_completion(messages, tools, temperature, max_tokens, enable_thinking)
457
+
458
+ raise RuntimeError(
459
+ "\n╭────────────────────────────────────────────────────────────╮\n"
460
+ "│ iOS Native Inference: │\n"
461
+ "│ Dynamic compilation via pip is disabled on iOS. │\n"
462
+ "│ llama.cpp must be pre-bundled with the iOS app container │\n"
463
+ "│ or served via a local bridge (e.g. http://127.0.0.1:8080). │\n"
464
+ "╰────────────────────────────────────────────────────────────╯"
465
+ )
466
+
467
+ def _bridge_chat_completion(
468
+ self,
469
+ messages: List[dict],
470
+ tools: Optional[List[dict]] = None,
471
+ temperature: float = 0.2,
472
+ max_tokens: int = 2048,
473
+ enable_thinking: bool = True,
474
+ ) -> ChatResponse:
475
+ import httpx
476
+ import json
477
+ bridge_url = self._get_bridge_url()
478
+ sanitized = self._sanitize_messages_for_gguf(messages)
479
+ payload = {
480
+ "model": "local",
481
+ "messages": sanitized,
482
+ "temperature": temperature,
483
+ "max_tokens": max_tokens,
484
+ "stream": False,
485
+ }
486
+ if tools:
487
+ payload["tools"] = tools
488
+ payload["tool_choice"] = "auto"
489
+ resp = httpx.post(f"{bridge_url}/v1/chat/completions", json=payload, timeout=90.0)
490
+ if resp.status_code != 200:
491
+ raise RuntimeError(f"iOS bridge HTTP {resp.status_code}: {resp.text}")
492
+ data = json.loads(resp.text)
493
+ choice = data["choices"][0]["message"]
494
+ content = choice.get("content")
495
+ reasoning = choice.get("reasoning") or choice.get("reasoning_content")
496
+ raw_tc = choice.get("tool_calls")
497
+ tool_calls = None
498
+ if raw_tc:
499
+ tool_calls = []
500
+ for tc in raw_tc:
501
+ fn = tc.get("function", {})
502
+ args = fn.get("arguments", "{}")
503
+ if isinstance(args, str):
504
+ try:
505
+ args = json.loads(args)
506
+ except Exception:
507
+ args = {}
508
+ tool_calls.append(ToolCall(id=tc.get("id", "call_1"), name=fn.get("name", ""), arguments=args))
509
+ return ChatResponse(content=content, reasoning=reasoning, tool_calls=tool_calls, raw=data)
510
+
511
+ def chat_completion_stream(
512
+ self,
513
+ messages: List[dict],
514
+ tools: Optional[List[dict]] = None,
515
+ temperature: Optional[float] = None,
516
+ max_tokens: Optional[int] = None,
517
+ enable_thinking: bool = True,
518
+ ):
519
+ try:
520
+ import llama_cpp
521
+ yield from super().chat_completion_stream(messages, tools, temperature, max_tokens, enable_thinking)
522
+ return
523
+ except ImportError:
524
+ pass
525
+
526
+ if self._is_bridge_online():
527
+ yield from self._bridge_chat_completion_stream(messages, tools, temperature, max_tokens, enable_thinking)
528
+ return
529
+
530
+ raise RuntimeError(
531
+ "\n╭────────────────────────────────────────────────────────────╮\n"
532
+ "│ iOS Native Inference: │\n"
533
+ "│ Dynamic compilation via pip is disabled on iOS. │\n"
534
+ "│ llama.cpp must be pre-bundled with the iOS app container │\n"
535
+ "│ or served via a local bridge (e.g. http://127.0.0.1:8080). │\n"
536
+ "╰────────────────────────────────────────────────────────────╯"
537
+ )
538
+
539
+ def _bridge_chat_completion_stream(
540
+ self,
541
+ messages: List[dict],
542
+ tools: Optional[List[dict]] = None,
543
+ temperature: Optional[float] = None,
544
+ max_tokens: Optional[int] = None,
545
+ enable_thinking: bool = True,
546
+ ):
547
+ import httpx
548
+ import json
549
+ bridge_url = self._get_bridge_url()
550
+ sanitized = self._sanitize_messages_for_gguf(messages)
551
+ payload = {
552
+ "model": "local",
553
+ "messages": sanitized,
554
+ "temperature": temperature or 0.2,
555
+ "max_tokens": max_tokens or 2048,
556
+ "stream": True,
557
+ }
558
+ if tools:
559
+ payload["tools"] = tools
560
+ payload["tool_choice"] = "auto"
561
+ client = httpx.Client(timeout=90.0)
562
+ req = client.build_request("POST", f"{bridge_url}/v1/chat/completions", json=payload)
563
+ resp = client.send(req, stream=True)
564
+ if resp.status_code != 200:
565
+ err = resp.read().decode("utf-8", errors="replace")
566
+ resp.close()
567
+ raise RuntimeError(f"iOS bridge HTTP {resp.status_code}: {err}")
568
+ full_content = []
569
+ full_reasoning = []
570
+ tool_calls = []
571
+ try:
572
+ for line in resp.iter_lines():
573
+ line = line.strip()
574
+ if not line or not line.startswith("data: "):
575
+ continue
576
+ data_str = line[6:].strip()
577
+ if data_str == "[DONE]":
578
+ break
579
+ try:
580
+ chunk = json.loads(data_str)
581
+ except Exception:
582
+ continue
583
+ choice = chunk["choices"][0]
584
+ delta = choice.get("delta") or {}
585
+ if delta.get("content"):
586
+ full_content.append(delta["content"])
587
+ yield ("token", {"delta": delta["content"]})
588
+ if delta.get("reasoning") or delta.get("reasoning_content"):
589
+ r = delta.get("reasoning") or delta.get("reasoning_content")
590
+ full_reasoning.append(r)
591
+ yield ("thinking_delta", {"delta": r})
592
+ finally:
593
+ resp.close()
594
+ client.close()
595
+ yield ("done", ChatResponse(
596
+ content="".join(full_content).strip(),
597
+ reasoning="".join(full_reasoning).strip() or None,
598
+ tool_calls=tool_calls or None,
599
+ ))
600
+
601
+
602
+ class AndroidBackend(BasePlatformBackend):
603
+ """Android-specific inference backend (Termux or Android app)."""
604
+
605
+ @property
606
+ def platform_name(self) -> str:
607
+ return "Android"
608
+
609
+ @property
610
+ def is_available(self) -> bool:
611
+ try:
612
+ import llama_cpp
613
+ return True
614
+ except ImportError:
615
+ return bool(shutil.which("llama-server") or shutil.which("llama-cli"))
616
+
617
+
618
+ class MacOSBackend(BasePlatformBackend):
619
+ """macOS-specific inference backend with Metal acceleration."""
620
+
621
+ @property
622
+ def platform_name(self) -> str:
623
+ return "macOS Metal"
624
+
625
+
626
+ class WindowsBackend(BasePlatformBackend):
627
+ """Windows-specific inference backend with Vulkan/CUDA acceleration."""
628
+
629
+ @property
630
+ def platform_name(self) -> str:
631
+ return "Windows Vulkan"
632
+
633
+
634
+ class LinuxBackend(BasePlatformBackend):
635
+ """Linux-specific inference backend with CUDA/Vulkan/CPU acceleration."""
636
+
637
+ @property
638
+ def platform_name(self) -> str:
639
+ return "Linux"
640
+
641
+
642
+ def get_platform_backend(cfg: Config) -> BasePlatformBackend:
643
+ """Detect host OS and return the corresponding platform InferenceBackend."""
644
+ if is_ios():
645
+ return iOSBackend(cfg)
646
+ elif is_android():
647
+ return AndroidBackend(cfg)
648
+ elif sys.platform == "darwin":
649
+ return MacOSBackend(cfg)
650
+ elif sys.platform == "win32":
651
+ return WindowsBackend(cfg)
652
+ else:
653
+ return LinuxBackend(cfg)
654
+
655
+
656
+
657
+ __all__ = [
658
+ "BasePlatformBackend",
659
+ "iOSBackend",
660
+ "AndroidBackend",
661
+ "MacOSBackend",
662
+ "WindowsBackend",
663
+ "LinuxBackend",
664
+ "LocalBackend",
665
+ "get_platform_backend",
666
+ ]
667
+
@@ -14,7 +14,10 @@ from dataclasses import dataclass, asdict, fields
14
14
  from pathlib import Path
15
15
  from typing import Optional
16
16
 
17
- from .paths import ensure_dir, get_alpiecode_dir
17
+ from .paths import ensure_dir, get_alpiecode_dir, load_dotenv_if_present
18
+
19
+ # Auto-load .env if present (zero-dependency)
20
+ load_dotenv_if_present()
18
21
 
19
22
 
20
23
  def get_config_dir() -> Path:
@@ -40,14 +43,18 @@ CONFIG_DIR = get_alpiecode_dir()
40
43
  CONFIG_PATH = get_config_path()
41
44
 
42
45
  # Config version — bump this when defaults change to trigger auto-migration
43
- CONFIG_VERSION = 8 # v7: autonomous discovery engine (zero-flag flow)
46
+ CONFIG_VERSION = 10 # v10: Secure .env resolution for HF_TOKEN
47
+
48
+ # Read Hugging Face token securely from .env or environment variables
49
+ DEFAULT_HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or ""
50
+ DEFAULT_MODEL_REPO = "169Pi/alpie_learn_gguf"
44
51
 
45
52
  DEFAULTS = {
46
53
  "base_url": "https://test.169pi.ai/v1", # Primary endpoint
47
54
  "model": "alpie_9b",
48
- "model_repo": "169Pi/Alpie_learn_prototype_GGUF_NEW",
55
+ "model_repo": DEFAULT_MODEL_REPO,
49
56
  "api_key": "not-needed",
50
- "hf_token": None,
57
+ "hf_token": DEFAULT_HF_TOKEN,
51
58
  "max_turns": 200,
52
59
  "temperature": 0.1,
53
60
  "max_tokens": 8192,
@@ -122,9 +129,9 @@ def get_shared_http_client():
122
129
  class Config:
123
130
  base_url: Optional[str] = None
124
131
  model: str = "alpie_9b" # Server API model name (vLLM)
125
- model_repo: str = "169Pi/Alpie_learn_prototype_GGUF_NEW" # HuggingFace repo for offline GGUF
132
+ model_repo: str = DEFAULT_MODEL_REPO # HuggingFace repo for offline GGUF
126
133
  api_key: str = "not-needed"
127
- hf_token: Optional[str] = None
134
+ hf_token: Optional[str] = DEFAULT_HF_TOKEN
128
135
  max_turns: int = 200 # Safety ceiling only — agent runs until DONE
129
136
  temperature: float = 0.1
130
137
  max_tokens: int = 8192
@@ -152,12 +159,16 @@ def load_config() -> Config:
152
159
  data["n_ctx"] = 32768
153
160
  data["base_url"] = "https://test.169pi.ai/v1"
154
161
  data["model"] = "alpie_9b"
162
+ data["model_repo"] = DEFAULT_MODEL_REPO
163
+ data["hf_token"] = DEFAULT_HF_TOKEN
155
164
  data["enable_thinking"] = False
156
165
  data["temperature"] = 0.1
157
166
  data["max_tokens"] = 8192
158
167
  data["max_turns"] = 200
159
168
  data["config_version"] = CONFIG_VERSION
160
169
  needs_save = True
170
+ elif not data.get("hf_token"):
171
+ data["hf_token"] = DEFAULT_HF_TOKEN
161
172
  except Exception:
162
173
  pass
163
174
 
@@ -179,6 +190,8 @@ def load_config() -> Config:
179
190
  data["api_key"] = os.environ[f"{prefix}API_KEY"]
180
191
  if os.environ.get("HF_TOKEN"):
181
192
  data["hf_token"] = os.environ["HF_TOKEN"]
193
+ elif os.environ.get("HUGGING_FACE_HUB_TOKEN"):
194
+ data["hf_token"] = os.environ["HUGGING_FACE_HUB_TOKEN"]
182
195
 
183
196
  # Context size overrides from environment
184
197
  for ctx_var in ("ALPIECODE_N_CTX", "ALPIECODE_CTX_SIZE", "ALPIECODE_CONTEXT_SIZE", "CODEAGENT_N_CTX"):
@@ -229,21 +242,11 @@ def save_config(cfg: Config) -> None:
229
242
  def interactive_init() -> Config:
230
243
  current = load_config()
231
244
  print("AlpieCode Setup — Local GGUF Model Configuration\n")
245
+ print(f"AlpieCode is pre-configured with the {DEFAULT_MODEL_REPO} Q3 model.")
246
+ print("HuggingFace access tokens are securely read from .env or the HF_TOKEN environment variable.\n")
232
247
 
233
- print("AlpieCode uses the 169Pi/Alpie_learn_prototype_GGUF_NEW model from HuggingFace.")
234
- print("Please enter your HuggingFace user access token (required to download model).\n")
235
-
236
- # Mask token for display (show first 3 + last 3 chars only)
237
- if current.hf_token:
238
- t = current.hf_token
239
- masked = f"{t[:3]}***{t[-3:]}" if len(t) > 6 else "***"
240
- else:
241
- masked = "none"
242
- token_prompt = f"HuggingFace Token [{masked}]: "
243
- hf_token = input(token_prompt).strip() or current.hf_token
244
-
245
- repo_prompt = f"Model Repo [{current.model_repo}]: "
246
- model_repo = input(repo_prompt).strip() or current.model_repo
248
+ hf_token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or current.hf_token or DEFAULT_HF_TOKEN
249
+ model_repo = os.environ.get("ALPIECODE_MODEL_REPO") or current.model_repo or DEFAULT_MODEL_REPO
247
250
 
248
251
  cfg = Config(
249
252
  base_url=current.base_url,
@@ -12,7 +12,10 @@ import sys
12
12
  from pathlib import Path
13
13
  from typing import Any, Dict, List, Optional
14
14
 
15
- from .paths import ensure_dir, get_alpiecode_dir
15
+ from .paths import ensure_dir, get_alpiecode_dir, is_android, is_ios, load_dotenv_if_present
16
+
17
+ # Auto-load .env if present (zero-dependency)
18
+ load_dotenv_if_present()
16
19
 
17
20
 
18
21
  def get_model_cache_dir() -> Path:
@@ -20,7 +23,8 @@ def get_model_cache_dir() -> Path:
20
23
 
21
24
 
22
25
  CACHE_DIR = get_alpiecode_dir() / "models"
23
- DEFAULT_REPO = "169Pi/Alpie_learn_prototype_GGUF_NEW"
26
+ DEFAULT_HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or ""
27
+ DEFAULT_REPO = "169Pi/alpie_learn_gguf"
24
28
  DEFAULT_CTX_SIZE = 32768 # 32k tokens default for fast loading (supports up to 256k)
25
29
 
26
30
  # Preload WSL NVIDIA CUDA driver if running under WSL
@@ -119,24 +123,30 @@ def detect_gpu() -> int:
119
123
 
120
124
  def download_model(repo_id: str = DEFAULT_REPO, token: Optional[str] = None) -> Path:
121
125
  """
122
- Download single GGUF model from HuggingFace using huggingface_hub.
123
- Saves to ~/.alpiecode/models/ and returns the local Path.
126
+ Download GGUF text model and vision projector from HuggingFace using huggingface_hub.
127
+ Saves to ~/.alpiecode/models/ (or $ALPIECODE_HOME/models/) and returns the local Path.
124
128
 
125
- OFFLINE-FIRST: Checks local cache before any network call.
129
+ OFFLINE-FIRST: Checks local cache for BOTH text and vision models before network calls.
126
130
  """
127
131
  cache_dir = ensure_dir(get_model_cache_dir())
128
- hf_token = token or os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
132
+ raw_token = token or os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or DEFAULT_HF_TOKEN
133
+ hf_token = raw_token.strip() if (isinstance(raw_token, str) and raw_token.strip()) else None
129
134
 
130
135
  # ── STEP 1: Check local cache FIRST (zero network) ───────────────
131
- local_gguf = list(cache_dir.glob("*.gguf"))
132
- # Filter out mmproj files for main model
133
- local_main = [f for f in local_gguf if "mmproj" not in f.name.lower()]
134
- if local_main:
135
- return local_main[0]
136
- if local_gguf:
137
- return local_gguf[0]
138
-
139
- # ── STEP 2: Model not cached — must download from HuggingFace ────
136
+ local_ggufs = list(cache_dir.glob("*.gguf"))
137
+ local_main_candidates = [f for f in local_ggufs if "mmproj" not in f.name.lower()]
138
+ local_mmproj_candidates = [f for f in local_ggufs if "mmproj" in f.name.lower()]
139
+
140
+ # Prefer Q3 model if multiple local models exist
141
+ local_q3 = [f for f in local_main_candidates if "q3" in f.name.lower()]
142
+ active_local_main = local_q3[0] if local_q3 else (local_main_candidates[0] if local_main_candidates else None)
143
+ active_local_mmproj = local_mmproj_candidates[0] if local_mmproj_candidates else None
144
+
145
+ # If BOTH text model and vision projector are already present in cache, return immediately!
146
+ if active_local_main and active_local_mmproj:
147
+ return active_local_main
148
+
149
+ # ── STEP 2: One or both models missing — download from HuggingFace ────
140
150
  try:
141
151
  from huggingface_hub import hf_hub_download, list_repo_files
142
152
  except ImportError:
@@ -144,93 +154,86 @@ def download_model(repo_id: str = DEFAULT_REPO, token: Optional[str] = None) ->
144
154
  "huggingface_hub package is missing. Install it with: pip install huggingface_hub"
145
155
  )
146
156
 
147
- # List files in repo to find the GGUF file
157
+ # List files in repo to find text model and vision projector
148
158
  try:
149
159
  files = list_repo_files(repo_id=repo_id, token=hf_token)
150
160
  gguf_files = [f for f in files if f.endswith(".gguf")]
151
161
  except Exception as e:
152
162
  err_str = str(e).lower()
153
- # Differentiate auth/access errors vs network errors
154
163
  if "401" in err_str or "unauthorized" in err_str:
155
164
  raise RuntimeError(
156
165
  f"\n❌ HuggingFace Authentication Failed for '{repo_id}'.\n"
157
- " Your HF token is invalid or expired.\n"
158
- " → Go to https://huggingface.co/settings/tokens to generate a new token.\n"
159
- " → Then run: alpiecode init"
166
+ " The repository is private or requires authentication.\n"
167
+ " Please provide a HuggingFace token via:\n"
168
+ " 1. A .env file in your working directory: HF_TOKEN=your_token\n"
169
+ " 2. Environment variable: export HF_TOKEN=your_token\n"
170
+ " 3. Or make the HuggingFace repository Public."
160
171
  ) from e
161
172
  elif "403" in err_str or "forbidden" in err_str or "storage limit" in err_str:
162
173
  raise RuntimeError(
163
174
  f"\n❌ HuggingFace Access Denied (403) for '{repo_id}'.\n"
164
- " Your token does not have access to this private repo.\n"
165
- " → Ask the 169Pi team to grant you access, or check your token permissions."
175
+ " Repository storage limit or permission restriction encountered."
166
176
  ) from e
167
177
  elif "404" in err_str or "not found" in err_str:
168
178
  raise RuntimeError(
169
- f"\n❌ HuggingFace repo '{repo_id}' not found (404).\n"
170
- " The model repository may not exist or is private.\n"
171
- " → Verify the repo name and ensure your HF token has read access."
179
+ f"\n❌ HuggingFace repo '{repo_id}' not found (404)."
172
180
  ) from e
173
181
  else:
182
+ # If we at least have the text model cached, proceed offline
183
+ if active_local_main:
184
+ return active_local_main
174
185
  raise RuntimeError(
175
186
  "\n╭──────────────────────────────────────────────────────────────╮\n"
176
187
  "│ GGUF model not found locally and could not download. │\n"
177
188
  "│ │\n"
178
189
  f"│ Error: {str(e)[:52]:<53}│\n"
179
190
  "│ │\n"
180
- "│ Connect to internet and run: │\n"
181
- "│ alpiecode init │\n"
182
- "│ │\n"
183
191
  "│ After the one-time download, offline mode works forever. │\n"
184
192
  "╰──────────────────────────────────────────────────────────────╯"
185
193
  ) from e
186
194
 
187
- # Separate main model file from mmproj (vision projector) file
188
195
  main_gguf_files = [f for f in gguf_files if "mmproj" not in f.lower()]
189
196
  mmproj_files = [f for f in gguf_files if "mmproj" in f.lower()]
190
197
 
191
- if not main_gguf_files:
192
- main_gguf_files = gguf_files
198
+ # Explicitly prioritize Q3 text model over Q4 or others
199
+ q3_files = [f for f in main_gguf_files if "q3" in f.lower()]
200
+ target_main_file = q3_files[0] if q3_files else (main_gguf_files[0] if main_gguf_files else None)
193
201
 
194
- target_file = main_gguf_files[0]
195
- cached_file = cache_dir / target_file
202
+ if not target_main_file:
203
+ raise RuntimeError(f"No GGUF text model found in repository '{repo_id}'.")
196
204
 
197
- if not cached_file.exists():
198
- print(f"📥 Downloading local model from HuggingFace ({repo_id}/{target_file})...")
199
- print(" This is a one-time download. Subsequent runs will work 100% offline.")
205
+ cached_main = cache_dir / target_main_file
206
+ if not cached_main.exists():
207
+ print(f"📥 [1/2] Downloading Alpie Q3 text model ({repo_id}/{target_main_file})...")
208
+ print(" This is a one-time download (~4.6 GB). Subsequent runs work 100% offline.")
200
209
  try:
201
210
  hf_hub_download(
202
211
  repo_id=repo_id,
203
- filename=target_file,
212
+ filename=target_main_file,
204
213
  local_dir=cache_dir,
205
214
  token=hf_token,
206
215
  )
207
216
  except Exception as e:
208
- err_str = str(e)
209
- if "403" in err_str or "storage limit" in err_str.lower() or "forbidden" in err_str.lower():
210
- raise RuntimeError(
211
- f"HuggingFace 403 Forbidden Error for repo '{repo_id}':\n"
212
- " 'Private repository storage limit reached for 169Pi account.'\n"
213
- " 💡 Please ask your 169Pi organization admin to upgrade the HF storage plan or free up space on HuggingFace."
214
- ) from e
215
- raise RuntimeError(f"HuggingFace Download Failed for '{repo_id}/{target_file}': {e}") from e
216
-
217
- # Download mmproj file if available (for vision features)
217
+ raise RuntimeError(f"Failed to download text model '{target_main_file}': {e}") from e
218
+
219
+ # Download vision projector (mmproj) if available
218
220
  if mmproj_files:
219
- mmproj_target = mmproj_files[0]
220
- mmproj_cached = cache_dir / mmproj_target
221
- if not mmproj_cached.exists():
221
+ target_mmproj_file = mmproj_files[0]
222
+ cached_mmproj = cache_dir / target_mmproj_file
223
+ if not cached_mmproj.exists():
224
+ print(f"📥 [2/2] Downloading Alpie vision projector ({repo_id}/{target_mmproj_file})...")
222
225
  try:
223
- print(f"📥 Downloading vision projector ({repo_id}/{mmproj_target})...")
224
226
  hf_hub_download(
225
227
  repo_id=repo_id,
226
- filename=mmproj_target,
228
+ filename=target_mmproj_file,
227
229
  local_dir=cache_dir,
228
230
  token=hf_token,
229
231
  )
230
232
  except Exception as e:
231
- print(f"⚠️ Could not download vision projector ({mmproj_target}): {e}")
233
+ print(f"⚠️ Could not download vision projector ({target_mmproj_file}): {e}")
234
+
235
+ return cached_main
232
236
 
233
- return cached_file
234
237
 
235
238
 
236
239
  # ── Local Model Engine Class ──────────────────────────────────────────
@@ -243,6 +246,26 @@ def _ensure_llama_cpp():
243
246
  except ImportError:
244
247
  pass
245
248
 
249
+ if is_ios():
250
+ raise RuntimeError(
251
+ "\n╭────────────────────────────────────────────────────────────╮\n"
252
+ "│ iOS Native Inference: │\n"
253
+ "│ Dynamic compilation via pip is disabled on iOS. │\n"
254
+ "│ llama.cpp must be pre-bundled with the iOS app container │\n"
255
+ "│ or served via a local bridge (e.g. http://127.0.0.1:8080). │\n"
256
+ "╰────────────────────────────────────────────────────────────╯"
257
+ )
258
+
259
+ if is_android():
260
+ raise RuntimeError(
261
+ "\n╭────────────────────────────────────────────────────────────╮\n"
262
+ "│ Android / Termux Native Inference: │\n"
263
+ "│ Dynamic pip compilation is disabled on Android. │\n"
264
+ "│ To enable local inference on Termux, please install: │\n"
265
+ "│ pkg install llama.cpp │\n"
266
+ "╰────────────────────────────────────────────────────────────╯"
267
+ )
268
+
246
269
  print("⚙️ Auto-installing pre-compiled local GGUF engine (one-time setup)...")
247
270
  import sys
248
271
  import subprocess
@@ -319,7 +342,7 @@ class LocalModel:
319
342
  self.repo_id = repo_id
320
343
  self.n_ctx = n_ctx
321
344
  self.n_gpu_layers = n_gpu_layers if n_gpu_layers is not None else detect_gpu()
322
- self.token = token
345
+ self.token = token or DEFAULT_HF_TOKEN
323
346
  self.model_path: Optional[Path] = None
324
347
  self._llm = None
325
348
 
@@ -337,6 +360,11 @@ class LocalModel:
337
360
  model_path = self.ensure_model()
338
361
  Llama = _ensure_llama_cpp()
339
362
 
363
+ # Locate vision projector if cached
364
+ cache_dir = ensure_dir(get_model_cache_dir())
365
+ mmproj_files = list(cache_dir.glob("*mmproj*.gguf"))
366
+ mmproj_path = mmproj_files[0] if mmproj_files else None
367
+
340
368
  has_gpu_offload = False
341
369
  try:
342
370
  import llama_cpp
@@ -372,6 +400,8 @@ class LocalModel:
372
400
  pass
373
401
 
374
402
  print(f"🧠 Loading local GGUF model: {model_path.name}")
403
+ if mmproj_path:
404
+ print(f" Vision Projector: {mmproj_path.name} (Multimodal Ready)")
375
405
  print(f" Context: {self.n_ctx} tokens | Mode: {accel} | Threads: {n_threads}")
376
406
  if accel == "CPU":
377
407
  print(f" ⏳ CPU loading ~4GB model — this takes 30-90 seconds on first run...")
@@ -405,6 +435,13 @@ class LocalModel:
405
435
  verbose=False,
406
436
  )
407
437
 
438
+ if mmproj_path and mmproj_path.exists():
439
+ try:
440
+ from llama_cpp.llama_chat_format import Llava15ChatHandler
441
+ llama_kwargs["chat_handler"] = Llava15ChatHandler(clip_model_path=str(mmproj_path))
442
+ except Exception:
443
+ pass
444
+
408
445
  # Quantized KV Cache (Q8_0) — halves VRAM usage, ~0% quality loss
409
446
  # Only enable for GPU mode where VRAM savings matter
410
447
  if self.n_gpu_layers != 0:
@@ -0,0 +1,115 @@
1
+ """
2
+ Cross-platform path resolution for AlpieCode.
3
+
4
+ Supports iOS, Android, Linux, macOS, and Windows without hardcoded home directories.
5
+ Resolution order:
6
+ 1. ALPIECODE_HOME environment variable (override)
7
+ 2. Project/working directory: Path.cwd() / ".alpiecode"
8
+ 3. Resilient fallback to Path.home() / ".alpiecode" or tempfile
9
+ """
10
+
11
+ import os
12
+ import tempfile
13
+ from pathlib import Path
14
+ from typing import Optional
15
+
16
+
17
+ def get_alpiecode_dir() -> Path:
18
+ """
19
+ Return the base directory for AlpieCode state, caches, and trajectories.
20
+ User can override the location if needed via ALPIECODE_HOME.
21
+ Default: project/current working directory (.alpiecode).
22
+ """
23
+ custom_dir = os.environ.get("ALPIECODE_HOME")
24
+ if custom_dir:
25
+ return Path(custom_dir).expanduser()
26
+ return Path.cwd() / ".alpiecode"
27
+
28
+
29
+ def ensure_dir(path: Path) -> Path:
30
+ """Safely create directory with resilient fallback if path is not writable."""
31
+ try:
32
+ path.mkdir(parents=True, exist_ok=True)
33
+ return path
34
+ except (PermissionError, OSError):
35
+ fallback = Path(tempfile.gettempdir()) / ".alpiecode" / path.name
36
+ try:
37
+ fallback.mkdir(parents=True, exist_ok=True)
38
+ return fallback
39
+ except Exception:
40
+ return path
41
+
42
+
43
+ def is_ios() -> bool:
44
+ """Detect if running on iOS (Pythonista, a-Shell, Pyto, iSH, or iOS app container)."""
45
+ import sys
46
+ if sys.platform == "ios":
47
+ return True
48
+ if sys.platform == "darwin":
49
+ try:
50
+ machine = os.uname().machine.lower()
51
+ if any(device in machine for device in ("iphone", "ipad", "ipod")):
52
+ return True
53
+ except Exception:
54
+ pass
55
+ if any(os.environ.get(k) for k in ("IPHONEOS", "IOS_APP", "IS_IOS", "PYTO_APP", "PYTHONISTA_APP")):
56
+ return True
57
+ if hasattr(sys, "getiosversion"):
58
+ return True
59
+ return os.environ.get("ALPIECODE_PLATFORM", "").lower() == "ios"
60
+
61
+
62
+ def is_android() -> bool:
63
+ """Detect if running on Android (Termux or Android app)."""
64
+ if os.environ.get("ANDROID_ROOT") or os.environ.get("ANDROID_DATA"):
65
+ return True
66
+ if "com.termux" in os.environ.get("PREFIX", ""):
67
+ return True
68
+ return os.environ.get("ALPIECODE_PLATFORM", "").lower() == "android"
69
+
70
+
71
+ def load_dotenv_if_present(dotenv_path: Optional[Path] = None) -> None:
72
+ """
73
+ Lightweight, pure-Python .env file loader (zero external dependencies).
74
+ Loads variables into os.environ without overwriting existing environment variables.
75
+ Checks:
76
+ 1. Explicit dotenv_path (if provided)
77
+ 2. Path.cwd() / ".env"
78
+ 3. get_alpiecode_dir() / ".env"
79
+ 4. Path.home() / ".alpiecode" / ".env" (fallback)
80
+ """
81
+ candidates = []
82
+ if dotenv_path:
83
+ candidates.append(Path(dotenv_path))
84
+ else:
85
+ candidates.append(Path.cwd() / ".env")
86
+ candidates.append(get_alpiecode_dir() / ".env")
87
+ try:
88
+ candidates.append(Path.home() / ".alpiecode" / ".env")
89
+ except Exception:
90
+ pass
91
+
92
+ for candidate in candidates:
93
+ if candidate.is_file():
94
+ try:
95
+ with open(candidate, "r", encoding="utf-8") as f:
96
+ for line in f:
97
+ line = line.strip()
98
+ if not line or line.startswith("#"):
99
+ continue
100
+ if line.startswith("export "):
101
+ line = line[7:].strip()
102
+ if "=" in line:
103
+ key, val = line.split("=", 1)
104
+ key = key.strip()
105
+ val = val.strip()
106
+ if len(val) >= 2 and (
107
+ (val.startswith('"') and val.endswith('"'))
108
+ or (val.startswith("'") and val.endswith("'"))
109
+ ):
110
+ val = val[1:-1]
111
+ if key and key not in os.environ:
112
+ os.environ[key] = val
113
+ except Exception:
114
+ pass
115
+
@@ -0,0 +1,238 @@
1
+ """
2
+ Tests for local model resolution, Q3 model prioritization, and embedded HuggingFace token.
3
+ """
4
+
5
+ import tempfile
6
+ from pathlib import Path
7
+ from unittest.mock import patch, MagicMock
8
+
9
+ import pytest
10
+
11
+ from codeagent.config import load_config, DEFAULT_HF_TOKEN, DEFAULT_MODEL_REPO
12
+ from codeagent.local_model import (
13
+ download_model,
14
+ DEFAULT_REPO,
15
+ DEFAULT_HF_TOKEN as LM_TOKEN,
16
+ LocalModel,
17
+ )
18
+
19
+
20
+ def test_config_and_token_defaults():
21
+ cfg = load_config()
22
+ assert cfg.model_repo == "169Pi/alpie_learn_gguf"
23
+ assert cfg.hf_token == DEFAULT_HF_TOKEN
24
+ assert DEFAULT_REPO == "169Pi/alpie_learn_gguf"
25
+ assert LM_TOKEN == DEFAULT_HF_TOKEN
26
+
27
+
28
+ def test_download_model_cached_both_files():
29
+ """When both Q3 text model and mmproj are present in cache, zero network calls should occur."""
30
+ with tempfile.TemporaryDirectory() as td:
31
+ cache_dir = Path(td)
32
+ (cache_dir / "alpie-vl-text-q3_k_m.gguf").touch()
33
+ (cache_dir / "alpie-vl-mmproj-f16.gguf").touch()
34
+
35
+ with patch("codeagent.local_model.get_model_cache_dir", return_value=cache_dir), \
36
+ patch("huggingface_hub.list_repo_files", side_effect=AssertionError("Network call made")):
37
+ target = download_model()
38
+ assert target.name == "alpie-vl-text-q3_k_m.gguf"
39
+
40
+
41
+ def test_download_model_downloads_both_text_and_vision():
42
+ """When neither file is present, both text and mmproj should be downloaded."""
43
+ with tempfile.TemporaryDirectory() as td:
44
+ cache_dir = Path(td)
45
+ mock_files = [
46
+ ".gitattributes",
47
+ "README.md",
48
+ "alpie-vl-mmproj-f16.gguf",
49
+ "alpie-vl-text-q3_k_m.gguf",
50
+ ]
51
+ downloaded = []
52
+
53
+ def mock_download(repo_id, filename, local_dir, token):
54
+ downloaded.append(filename)
55
+ (local_dir / filename).touch()
56
+
57
+ with patch("codeagent.local_model.get_model_cache_dir", return_value=cache_dir), \
58
+ patch("huggingface_hub.list_repo_files", return_value=mock_files), \
59
+ patch("huggingface_hub.hf_hub_download", side_effect=mock_download):
60
+ target = download_model()
61
+ assert target.name == "alpie-vl-text-q3_k_m.gguf"
62
+ assert "alpie-vl-text-q3_k_m.gguf" in downloaded
63
+ assert "alpie-vl-mmproj-f16.gguf" in downloaded
64
+
65
+
66
+ def test_download_model_downloads_missing_vision_only():
67
+ """When text file is present but mmproj is missing, it should download only mmproj."""
68
+ with tempfile.TemporaryDirectory() as td:
69
+ cache_dir = Path(td)
70
+ (cache_dir / "alpie-vl-text-q3_k_m.gguf").touch()
71
+
72
+ mock_files = [
73
+ ".gitattributes",
74
+ "README.md",
75
+ "alpie-vl-mmproj-f16.gguf",
76
+ "alpie-vl-text-q3_k_m.gguf",
77
+ ]
78
+ downloaded = []
79
+
80
+ def mock_download(repo_id, filename, local_dir, token):
81
+ downloaded.append(filename)
82
+ (local_dir / filename).touch()
83
+
84
+ with patch("codeagent.local_model.get_model_cache_dir", return_value=cache_dir), \
85
+ patch("huggingface_hub.list_repo_files", return_value=mock_files), \
86
+ patch("huggingface_hub.hf_hub_download", side_effect=mock_download):
87
+ target = download_model()
88
+ assert target.name == "alpie-vl-text-q3_k_m.gguf"
89
+ assert downloaded == ["alpie-vl-mmproj-f16.gguf"]
90
+
91
+
92
+ def test_platform_backend_dispatch(monkeypatch):
93
+ """Test that LocalBackend dispatches to the correct platform-specific backend."""
94
+ from codeagent.backends.local_backend import (
95
+ LocalBackend,
96
+ iOSBackend,
97
+ AndroidBackend,
98
+ LinuxBackend,
99
+ MacOSBackend,
100
+ WindowsBackend,
101
+ get_platform_backend,
102
+ )
103
+ cfg = load_config()
104
+
105
+ # iOS
106
+ monkeypatch.setenv("ALPIECODE_PLATFORM", "ios")
107
+ b_ios = LocalBackend(cfg)
108
+ assert isinstance(b_ios, iOSBackend)
109
+ assert isinstance(b_ios, LocalBackend)
110
+ assert b_ios.platform_name == "iOS"
111
+
112
+ # Android
113
+ monkeypatch.setenv("ALPIECODE_PLATFORM", "android")
114
+ b_android = LocalBackend(cfg)
115
+ assert isinstance(b_android, AndroidBackend)
116
+ assert isinstance(b_android, LocalBackend)
117
+ assert b_android.platform_name == "Android"
118
+
119
+ # Linux
120
+ monkeypatch.delenv("ALPIECODE_PLATFORM", raising=False)
121
+ monkeypatch.setattr("sys.platform", "linux")
122
+ b_linux = get_platform_backend(cfg)
123
+ assert isinstance(b_linux, LinuxBackend)
124
+ assert isinstance(b_linux, LocalBackend)
125
+
126
+ # Windows
127
+ monkeypatch.setattr("sys.platform", "win32")
128
+ b_win = get_platform_backend(cfg)
129
+ assert isinstance(b_win, WindowsBackend)
130
+ assert isinstance(b_win, LocalBackend)
131
+
132
+ # macOS
133
+ monkeypatch.setattr("sys.platform", "darwin")
134
+ monkeypatch.setattr("codeagent.paths.is_ios", lambda: False)
135
+ b_mac = get_platform_backend(cfg)
136
+ assert isinstance(b_mac, MacOSBackend)
137
+ assert isinstance(b_mac, LocalBackend)
138
+
139
+
140
+ def test_ios_backend_no_pip_compilation(monkeypatch):
141
+ """iOSBackend must NEVER attempt pip install or dynamic compilation."""
142
+ from codeagent.backends.local_backend import iOSBackend
143
+ cfg = load_config()
144
+ b = iOSBackend(cfg)
145
+
146
+ # Mock llama_cpp as missing and bridge offline
147
+ with patch.dict("sys.modules", {"llama_cpp": None}), \
148
+ patch("subprocess.run", side_effect=AssertionError("subprocess.run must never be called on iOS!")):
149
+ with pytest.raises(RuntimeError) as exc_info:
150
+ b.chat_completion([{"role": "user", "content": "hello"}])
151
+ assert "Dynamic compilation via pip is disabled on iOS" in str(exc_info.value)
152
+
153
+
154
+ def test_ios_backend_with_bridge():
155
+ """iOSBackend communicates cleanly with a local HTTP bridge when available."""
156
+ from codeagent.backends.local_backend import iOSBackend
157
+ cfg = load_config()
158
+ b = iOSBackend(cfg)
159
+
160
+ mock_resp = MagicMock()
161
+ mock_resp.status_code = 200
162
+ mock_resp.text = '{"choices": [{"message": {"content": "response from in-app bridge"}}]}'
163
+
164
+ with patch.dict("sys.modules", {"llama_cpp": None}), \
165
+ patch("httpx.get", return_value=mock_resp), \
166
+ patch("httpx.post", return_value=mock_resp):
167
+ assert b.is_available is True
168
+ res = b.chat_completion([{"role": "user", "content": "hello"}])
169
+ assert res.content == "response from in-app bridge"
170
+
171
+
172
+ def test_load_dotenv_custom_path(monkeypatch, tmp_path):
173
+ """Test pure-Python .env parsing with exports, comments, quotes, and existing vars."""
174
+ from codeagent.paths import load_dotenv_if_present
175
+ import os
176
+
177
+ env_file = tmp_path / ".env"
178
+ env_file.write_text(
179
+ "# Comment line\n"
180
+ "TEST_VAR_A=hello_world\n"
181
+ "export TEST_VAR_B=\"quoted_value\"\n"
182
+ "TEST_VAR_C='single_quoted'\n"
183
+ "EXISTING_VAR=new_value\n"
184
+ )
185
+
186
+ monkeypatch.setenv("EXISTING_VAR", "original_value")
187
+ monkeypatch.delenv("TEST_VAR_A", raising=False)
188
+ monkeypatch.delenv("TEST_VAR_B", raising=False)
189
+ monkeypatch.delenv("TEST_VAR_C", raising=False)
190
+
191
+ load_dotenv_if_present(dotenv_path=env_file)
192
+
193
+ assert os.environ.get("TEST_VAR_A") == "hello_world"
194
+ assert os.environ.get("TEST_VAR_B") == "quoted_value"
195
+ assert os.environ.get("TEST_VAR_C") == "single_quoted"
196
+ assert os.environ.get("EXISTING_VAR") == "original_value" # Preserved
197
+
198
+
199
+ def test_download_model_anonymous_token(monkeypatch):
200
+ """When no HF_TOKEN is configured, download_model passes token=None for public access."""
201
+ monkeypatch.delenv("HF_TOKEN", raising=False)
202
+ monkeypatch.delenv("HUGGING_FACE_HUB_TOKEN", raising=False)
203
+
204
+ with tempfile.TemporaryDirectory() as td:
205
+ cache_dir = Path(td)
206
+ captured_tokens = []
207
+
208
+ def mock_list_files(repo_id, token):
209
+ captured_tokens.append(token)
210
+ return ["alpie-vl-text-q3_k_m.gguf", "alpie-vl-mmproj-f16.gguf"]
211
+
212
+ def mock_download(repo_id, filename, local_dir, token):
213
+ captured_tokens.append(token)
214
+ (local_dir / filename).touch()
215
+
216
+ with patch("codeagent.local_model.get_model_cache_dir", return_value=cache_dir), \
217
+ patch("codeagent.local_model.DEFAULT_HF_TOKEN", ""), \
218
+ patch("huggingface_hub.list_repo_files", side_effect=mock_list_files), \
219
+ patch("huggingface_hub.hf_hub_download", side_effect=mock_download):
220
+ download_model(token=None)
221
+ assert None in captured_tokens
222
+
223
+
224
+ def test_download_model_401_error_guidance(monkeypatch):
225
+ """When a 401 Unauthorized occurs, AlpieCode gives clear guidance on .env and public repos."""
226
+ with tempfile.TemporaryDirectory() as td:
227
+ cache_dir = Path(td)
228
+
229
+ with patch("codeagent.local_model.get_model_cache_dir", return_value=cache_dir), \
230
+ patch("huggingface_hub.list_repo_files", side_effect=Exception("401 Client Error: Unauthorized for url")):
231
+ with pytest.raises(RuntimeError) as exc_info:
232
+ download_model()
233
+ err_msg = str(exc_info.value)
234
+ assert "HuggingFace Authentication Failed" in err_msg
235
+ assert ".env file" in err_msg
236
+ assert "HF_TOKEN" in err_msg
237
+ assert "make the HuggingFace repository Public" in err_msg
238
+
@@ -1,40 +0,0 @@
1
- """
2
- Cross-platform path resolution for AlpieCode.
3
-
4
- Supports iOS, Android, Linux, macOS, and Windows without hardcoded home directories.
5
- Resolution order:
6
- 1. ALPIECODE_HOME environment variable (override)
7
- 2. Project/working directory: Path.cwd() / ".alpiecode"
8
- 3. Resilient fallback to Path.home() / ".alpiecode" or tempfile
9
- """
10
-
11
- import os
12
- import tempfile
13
- from pathlib import Path
14
- from typing import Optional
15
-
16
-
17
- def get_alpiecode_dir() -> Path:
18
- """
19
- Return the base directory for AlpieCode state, caches, and trajectories.
20
- User can override the location if needed via ALPIECODE_HOME.
21
- Default: project/current working directory (.alpiecode).
22
- """
23
- custom_dir = os.environ.get("ALPIECODE_HOME")
24
- if custom_dir:
25
- return Path(custom_dir).expanduser()
26
- return Path.cwd() / ".alpiecode"
27
-
28
-
29
- def ensure_dir(path: Path) -> Path:
30
- """Safely create directory with resilient fallback if path is not writable."""
31
- try:
32
- path.mkdir(parents=True, exist_ok=True)
33
- return path
34
- except (PermissionError, OSError):
35
- fallback = Path(tempfile.gettempdir()) / ".alpiecode" / path.name
36
- try:
37
- fallback.mkdir(parents=True, exist_ok=True)
38
- return fallback
39
- except Exception:
40
- return path
File without changes
File without changes